/**
 *====================================================
 * 文件名称: EnterpriseActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月24日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.member.action.v1;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.starchain.smsender.SendMsgUtil;
import com.yuexunit.account.action.v2.AccountActionApi;
import com.yuexunit.account.action.v2.model.AccountAlias;
import com.yuexunit.account.action.v2.model.AccountNameType;
import com.yuexunit.account.entity.AccountNameEntity;
import com.yuexunit.account.entity.AccountPasswordEntity;
import com.yuexunit.account.service.AccountService;
import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.bulkstock.service.BulkstockInfoService;
import com.yuexunit.finance.bulkstock.service.TemporaryCreditlineEvaluationService;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.CollectionUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.common.util.RandomUtil;
import com.yuexunit.finance.context.FinanceConstant;
import com.yuexunit.finance.context.FinanceLetterBlockingQueue;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.esign.action.v1.EqianbaoActionApi;
import com.yuexunit.finance.esign.action.v1.model.output.EqbResult;
import com.yuexunit.finance.member.action.v1.dto.EnterpriseCastor;
import com.yuexunit.finance.member.action.v1.model.AbnormalDetailResult;
import com.yuexunit.finance.member.action.v1.model.AssociatedPerson;
import com.yuexunit.finance.member.action.v1.model.AuctionDetailResult;
import com.yuexunit.finance.member.action.v1.model.BusinessInfoDetailResult;
import com.yuexunit.finance.member.action.v1.model.Campaigners;
import com.yuexunit.finance.member.action.v1.model.CommissionScaleTable;
import com.yuexunit.finance.member.action.v1.model.CourtNoticeDetailResult;
import com.yuexunit.finance.member.action.v1.model.CustomerData;
import com.yuexunit.finance.member.action.v1.model.CustomerListData;
import com.yuexunit.finance.member.action.v1.model.EnterpriseAddressInfo;
import com.yuexunit.finance.member.action.v1.model.EnterpriseBaseDetail;
import com.yuexunit.finance.member.action.v1.model.EnterpriseBaseInfo;
import com.yuexunit.finance.member.action.v1.model.EnterpriseDetail;
import com.yuexunit.finance.member.action.v1.model.EnterpriseGradeEvaluation;
import com.yuexunit.finance.member.action.v1.model.EnterpriseGradeEvaluationDetail;
import com.yuexunit.finance.member.action.v1.model.EnterpriseInfo;
import com.yuexunit.finance.member.action.v1.model.EnterpriseLawsuitInfoDetailResult;
import com.yuexunit.finance.member.action.v1.model.EnterpriseNoticeDetailResult;
import com.yuexunit.finance.member.action.v1.model.EquityQualitiesDetailResult;
import com.yuexunit.finance.member.action.v1.model.ExecutedPersonDetailResult;
import com.yuexunit.finance.member.action.v1.model.ExecutionDetailResult;
import com.yuexunit.finance.member.action.v1.model.FinanceBulkstockPledgeRateDetail;
import com.yuexunit.finance.member.action.v1.model.FinanceFollowPersonDetail;
import com.yuexunit.finance.member.action.v1.model.MortgagesDetailResult;
import com.yuexunit.finance.member.action.v1.model.OverDueTaxDetailResult;
import com.yuexunit.finance.member.action.v1.model.Sponsor;
import com.yuexunit.finance.member.action.v1.model.SupplierInfo;
import com.yuexunit.finance.member.action.v1.model.TemporaryCreditlineEvaluation;
import com.yuexunit.finance.member.action.v1.model.TemporaryCreditlineEvaluationDetail;
import com.yuexunit.finance.member.entity.BankcodeEntity;
import com.yuexunit.finance.member.entity.CommissionScaleTableEntity;
import com.yuexunit.finance.member.entity.EnterpriseAddressEntity;
import com.yuexunit.finance.member.entity.EnterpriseCodeEntity;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEvaluationEntity;
import com.yuexunit.finance.member.entity.EnterpriseModifyEntity;
import com.yuexunit.finance.member.entity.FinanceBulkstockPledgeRateEntity;
import com.yuexunit.finance.member.entity.FinanceFollowInfoEntity;
import com.yuexunit.finance.member.entity.FinanceFollowPersonEntity;
import com.yuexunit.finance.member.entity.SupplierEntity;
import com.yuexunit.finance.member.entity.TemporaryCreditlineEvaluationEntity;
import com.yuexunit.finance.member.entity.lexicon.ApproveTypeEnum;
import com.yuexunit.finance.member.entity.lexicon.AuditStateEnum;
import com.yuexunit.finance.member.entity.lexicon.EnterpriseTypeEnum;
import com.yuexunit.finance.member.entity.lexicon.StateEnum;
import com.yuexunit.finance.member.service.CommissionScaleTableService;
import com.yuexunit.finance.member.service.EnterpriseAddressService;
import com.yuexunit.finance.member.service.EnterpriseCodeService;
import com.yuexunit.finance.member.service.EnterpriseGradeEvaluationService;
import com.yuexunit.finance.member.service.EnterpriseGradeService;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.member.service.FinanceBulkstockPledgeRateService;
import com.yuexunit.finance.member.service.FinanceFollowInfoService;
import com.yuexunit.finance.member.service.FinanceFollowPersonService;
import com.yuexunit.finance.member.service.SupplierService;
import com.yuexunit.finance.project.SettingConstants;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditLogEntity;
import com.yuexunit.finance.project.entity.FinanceCompleteResultEntity;
import com.yuexunit.finance.project.entity.FinanceEmployeeEntity;
import com.yuexunit.finance.project.entity.lexicon.ApiFinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ApiTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.DefaultAccountEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceAuditEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditLogService;
import com.yuexunit.finance.project.service.FinanceEmployeeService;
import com.yuexunit.finance.system.action.v1.dto.SendLetterMessage;
import com.yuexunit.finance.system.entity.DistrictInfoEntity;
import com.yuexunit.finance.system.service.DistrictInfoService;
import com.yuexunit.finance.thread.EnterpriseSummaryTimeTask;
import com.yuexunit.finance.zhanghuguangli.entity.EnterpriseAccountEntity;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.jsonutil.JSON;
import com.yuexunit.organization.OrganizationActionApi;
import com.yuexunit.organization.dto.CreateEmployee;
import com.yuexunit.organization.entity.OrgREmpEntity;
import com.yuexunit.organization.entity.OrganizationEntity;
import com.yuexunit.organization.service.OrganizationService;
import com.yuexunit.organization.service.PositionService;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.permission.action.PermissionActionsApi;
import com.yuexunit.permission.action.dto.RoleListDto;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.tenant.TenantActionApi;
import com.yuexunit.tenant.dto.TenantIdOutput;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;


/**
 * @ClassName: EnterpriseActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月24日 下午10:33:27
 */
@Implements(EnterpriseActionApi.class)
public class EnterpriseActionApiImpl implements EnterpriseActionApi {
	public static Logger logger = LoggerFactory.getLogger(EnterpriseActionApiImpl.class);

	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

	private EnterpriseGradeService enterpriseGradeService = ComponentFactory.loadClass(EnterpriseGradeService.class);

	private EnterpriseGradeEvaluationService enterpriseGradeEvaluationService = ComponentFactory.loadClass(EnterpriseGradeEvaluationService.class);

	private FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);

	private EnterpriseCodeService enterpriseCodeService = ComponentFactory.loadClass(EnterpriseCodeService.class);

	private TemporaryCreditlineEvaluationService temporaryCreditlineEvaluationService = ComponentFactory.loadClass(TemporaryCreditlineEvaluationService.class);

	private FinanceFollowPersonService financeFollowPersonService = ComponentFactory.loadClass(FinanceFollowPersonService.class);

	private FinanceFollowInfoService financeFollowInfoService = ComponentFactory.loadClass(FinanceFollowInfoService.class);

	private FinanceBulkstockPledgeRateService financeBulkstockPledgeRateService = ComponentFactory.loadClass(FinanceBulkstockPledgeRateService.class);

	private BulkstockInfoService bulkstockInfoService = ComponentFactory.loadClass(BulkstockInfoService.class);

	private FinanceAuditLogService financeAuditLogService = ComponentFactory.loadClass(FinanceAuditLogService.class);

	private PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);

	private DistrictInfoService districtInfoService = ComponentFactory.loadClass(DistrictInfoService.class);

	private AccountActionApi accountAction = ComponentFactory.loadClass(AccountActionApi.class);

	private TenantActionApi tenantAction = ComponentFactory.loadClass(TenantActionApi.class);

	private AccountService accountService = ComponentFactory.loadClass(AccountService.class);

	private OrganizationService organizationService = ComponentFactory.loadClass(OrganizationService.class);

	private OrganizationActionApi organizationActionApi = ComponentFactory.loadClass(OrganizationActionApi.class);

	private FinanceEmployeeService financeEmployeeService = ComponentFactory.loadClass(FinanceEmployeeService.class);

	private PositionService positionService = ComponentFactory.loadClass(PositionService.class);

	private CommissionScaleTableService commissionScaleTableService = ComponentFactory.loadClass(CommissionScaleTableService.class);

	private SupplierService supplierService = ComponentFactory.loadClass(SupplierService.class);

	private EnterpriseAddressService enterpriseAddressService = ComponentFactory.loadClass(EnterpriseAddressService.class);
	
	private EqianbaoActionApi eqianbaoActionApi = ComponentFactory.loadClass(EqianbaoActionApi.class);
	
	private String tmp = "客户(%s)资质认证目前处于资质认证审批环节对应的(%s)节点，请及时审批！";

	private List<Long> eIds = new ArrayList<>();

	@Override
	@Transactional
	public String createDistributor(String enterpriseName, String legalPerson, String mobile, String password,
			BigDecimal creditLine, String province, String city, String district, Long employeeId) {
		AccountNameEntity ane = accountService.inquireAccountName(mobile);
		if (ane != null) {
			throw new BusinessException("该账号已存在");
		}
		Long accountId = accountAction.createAccountSimple(mobile, password);

		AccountAlias accountAlias = new AccountAlias();
		accountAlias.setAccountId(accountId);
		accountAlias.setAccountName(mobile);
		accountAlias.setType(AccountNameType.MOBILE);
		accountAction.updateAccountAlias(accountAlias);
		// 创建租户信息
		TenantIdOutput tenantIdOutput = tenantAction.createTenantByAccountId(accountId, null);

		EnterpriseEntity enterprise = new EnterpriseEntity();
		initEnterprise(enterprise);
		enterprise.setEnterpriseName(enterpriseName);
		enterprise.setLegalPerson(legalPerson);
		enterprise.setMobile(mobile);
		enterprise.setProvince(province);
		enterprise.setCity(city);
		enterprise.setDistrict(district);
		enterprise.setEnterpriseType(EnterpriseTypeEnum.DISTRIBUTORS);
		enterprise.setCallback(Boolean.FALSE);
		enterprise.setSubmitState(Boolean.TRUE);
		enterprise.setAccountId(accountId);
		enterprise.setTenantId(tenantIdOutput.getTenantId());
		enterpriseService.createEnterprise(enterprise);
		enterprise.setAuditState(AuditStateEnum.FINISH);
		enterpriseService.updateEnterprise(enterprise);

		EnterpriseCodeEntity enterpriseCode = enterpriseCodeService.inquireEnterpriseCodeDetail(null, enterprise.getEnterpriseId());
		if (enterpriseCode == null) {
			enterpriseCode = new EnterpriseCodeEntity();
			enterpriseCode.setEnterpriseId(enterprise.getEnterpriseId());
			DistrictInfoEntity districtInfo = null;
			if (province.contains("辽宁") || province.contains("吉林") || province.contains("黑龙江")) {
				districtInfo = districtInfoService.inquireDistrictInfo(1L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(1L);
					districtInfo.setDistrictCode(10001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (province.contains("河北") || province.contains("天津") || province.contains("山西") || province.contains("内蒙")) {
				districtInfo = districtInfoService.inquireDistrictInfo(2L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(2L);
					districtInfo.setDistrictCode(20001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (province.contains("江苏") || province.contains("上海") || province.contains("安徽") || province.contains("江西") || province.contains("四川") || province.contains("重庆")) {
				districtInfo = districtInfoService.inquireDistrictInfo(3L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(3L);
					districtInfo.setDistrictCode(30001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (province.contains("广东")) {
				districtInfo = districtInfoService.inquireDistrictInfo(4L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(4L);
					districtInfo.setDistrictCode(40001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (province.contains("浙江") || province.contains("福建")) {
				districtInfo = districtInfoService.inquireDistrictInfo(5L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(5L);
					districtInfo.setDistrictCode(50001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (province.contains("广西") || province.contains("海南")) {
				districtInfo = districtInfoService.inquireDistrictInfo(6L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(6L);
					districtInfo.setDistrictCode(60001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (province.contains("山东")) {
				districtInfo = districtInfoService.inquireDistrictInfo(7L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(7L);
					districtInfo.setDistrictCode(70001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else {
				districtInfo = districtInfoService.inquireDistrictInfo(8L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(8L);
					districtInfo.setDistrictCode(00001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			}

			districtInfoService.updateDistrictInfo(districtInfo);
			enterpriseCode.setEnterpriseCode(String.valueOf(districtInfo.getDistrictCode()));
			enterpriseCodeService.createEnterpriseCode(enterpriseCode);
		} else {
			enterpriseCode.setEnterpriseId(enterprise.getEnterpriseId());
			enterpriseCodeService.createEnterpriseCode(enterpriseCode);
		}

		EnterpriseGradeEvaluation params = new EnterpriseGradeEvaluation();
		params.setCreditLine(creditLine);
		params.setEffectiveStartDate(DateUtils.getCurrentDate());
		params.setEffectiveEndDate(DateUtil.formatDate(DateUtil.tenYearsLater()));
		params.setEnterpriseId(enterprise.getEnterpriseId());

		EnterpriseGradeEvaluationEntity evaluation = EnterpriseCastor.fromEnterpriseGradeEvaluation(params);
		evaluation.setEffectiveStartDate(DateUtil.todayInt());
		evaluation.setEffectiveEndDate(DateUtils.parseDateInt(DateUtil.tenYearsLater()));
		evaluation.setAuditState(AuditStateEnum.PASS);
		if (evaluation.getGradeEvaluationId() == null || evaluation.getGradeEvaluationId() == 0L) {
			enterpriseGradeEvaluationService.createEnterpriseGradeEvaluation(evaluation);
		} else {
			enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(evaluation);
		}

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(params.getEnterpriseId());
		if (grade == null) {
			grade = new EnterpriseGradeEntity();
			grade.setEffective(Boolean.TRUE);
			BeanUtils.copyProperties(evaluation, grade);
			grade.setCreditAlready(BigDecimal.ZERO);
			enterpriseGradeService.createEnterpriseGrade(grade);
		} else {
			grade.setEffective(Boolean.TRUE);
			BeanUtils.copyProperties(evaluation, grade);
			grade.setCreditAlready(BigDecimal.ZERO);
			enterpriseGradeService.persistEnterpriseGrade(grade);
		}

		FinanceEmployeeEntity ee = financeEmployeeService.inquireEmployee(employeeId);
		FinanceFollowPersonEntity entity = new FinanceFollowPersonEntity();
		EnterpriseCodeEntity code = enterpriseCodeService.inquireEnterpriseCodeDetail(enterprise.getEnterpriseId());
		entity.setEnterpriseId(enterprise.getEnterpriseId());
		entity.setClientName(enterprise.getEnterpriseName());
		entity.setClientNumber(code.getEnterpriseCode());
		entity.setDateEnd(DateUtil.tenYearsLater());
		entity.setDateStart(DateUtil.now());
		entity.setFollowName(ee.getName());
		entity.setAccountId(ee.getAccountId());
		financeFollowPersonService.createFinanceFollowPerson(entity);

		synchronousToCrm(enterprise.getProvince() + enterprise.getCity() + enterprise.getDistrict(), enterprise.getLegalPerson(), enterprise.getMobile(), enterprise.getMobile(), String.valueOf(1));

		EnterpriseCastor.syncCustInfo(enterprise);

		return String.valueOf(enterprise.getEnterpriseId());
	}

	@Override
	public String registerEnterprise(EnterpriseBaseInfo enterpriseBaseInfo) {
		AccountNameEntity ane = accountService.inquireAccountName(enterpriseBaseInfo.getMobile());
		if (ane != null) {
			throw new BusinessException("该账号已存在");
		}

		EnterpriseCodeEntity code = null;
		if (FinanceSessionContext.isEnterprise()) {
			code = enterpriseCodeService.inquireEnterpriseCodeDetail(FinanceSessionContext.getEnterpriseId());
		}

		Long accountId = accountAction.createAccountSimple(enterpriseBaseInfo.getMobile(), "123456");
		AccountAlias accountAlias = new AccountAlias();
		accountAlias.setAccountId(accountId);
		accountAlias.setAccountName(enterpriseBaseInfo.getMobile());
		accountAlias.setType(AccountNameType.MOBILE);
		accountAction.updateAccountAlias(accountAlias);
		// 创建租户信息
		TenantIdOutput output = tenantAction.createTenantByAccountId(accountId, null);

		EnterpriseEntity enterprise = new EnterpriseEntity();
		if (code != null) {
			enterprise.setBelongsEnterpriseCode(code.getEnterpriseCode());
		}
		initEnterprise(enterprise);
		enterpriseService.inquireTenantEnterprise(output.getTenantId(), true, Boolean.TRUE);
		EnterpriseEntity entity = EnterpriseCastor.fromEnterpriseBaseInfo(enterpriseBaseInfo, enterprise);
		entity.setAccountId(accountId);
		entity.setTenantId(output.getTenantId());
		enterpriseService.createEnterprise(entity);

		EnterpriseCodeEntity enterpriseCode = enterpriseCodeService.inquireEnterpriseCodeDetail(null, entity.getEnterpriseId());
		if (enterpriseCode == null) {
			enterpriseCode = new EnterpriseCodeEntity();
			enterpriseCode.setEnterpriseId(entity.getEnterpriseId());
			DistrictInfoEntity districtInfo = null;
			if (enterpriseBaseInfo.getProvince().contains("辽宁") || enterpriseBaseInfo.getProvince().contains("吉林") || enterpriseBaseInfo.getProvince().contains("黑龙江")) {
				districtInfo = districtInfoService.inquireDistrictInfo(1L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(1L);
					districtInfo.setDistrictCode(10001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("河北") || enterpriseBaseInfo.getProvince().contains("天津") || enterpriseBaseInfo.getProvince().contains("山西") || enterpriseBaseInfo.getProvince().contains("内蒙")) {
				districtInfo = districtInfoService.inquireDistrictInfo(2L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(2L);
					districtInfo.setDistrictCode(20001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("江苏") || enterpriseBaseInfo.getProvince().contains("上海") || enterpriseBaseInfo.getProvince().contains("安徽") || enterpriseBaseInfo.getProvince().contains("江西") || enterpriseBaseInfo.getProvince().contains("四川") || enterpriseBaseInfo.getProvince().contains("重庆")) {
				districtInfo = districtInfoService.inquireDistrictInfo(3L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(3L);
					districtInfo.setDistrictCode(30001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("广东")) {
				districtInfo = districtInfoService.inquireDistrictInfo(4L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(4L);
					districtInfo.setDistrictCode(40001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("浙江") || enterpriseBaseInfo.getProvince().contains("福建")) {
				districtInfo = districtInfoService.inquireDistrictInfo(5L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(5L);
					districtInfo.setDistrictCode(50001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("广西") || enterpriseBaseInfo.getProvince().contains("海南")) {
				districtInfo = districtInfoService.inquireDistrictInfo(6L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(6L);
					districtInfo.setDistrictCode(60001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("山东")) {
				districtInfo = districtInfoService.inquireDistrictInfo(7L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(7L);
					districtInfo.setDistrictCode(70001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else {
				districtInfo = districtInfoService.inquireDistrictInfo(8L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(8L);
					districtInfo.setDistrictCode(00001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			}

			districtInfoService.updateDistrictInfo(districtInfo);
			enterpriseCode.setEnterpriseCode(String.valueOf(districtInfo.getDistrictCode()));
			enterpriseCodeService.createEnterpriseCode(enterpriseCode);
		} else {
			enterpriseCode.setEnterpriseId(entity.getEnterpriseId());
			enterpriseCodeService.createEnterpriseCode(enterpriseCode);
		}

		EnterpriseCastor.syncCustInfo(entity);

		return String.valueOf(entity.getEnterpriseId());
	}

	@Override
	public void syncCustInfo(Long enterpriseId) {
		EnterpriseEntity entity = enterpriseService.inquireEnterprise(enterpriseId);
		EnterpriseCastor.syncCustInfo(entity);
	}

	@Transactional
	@Override
	public void supplementRegisterEnterpriseImage(Long enterpriseId, String businessLicenceImage, String certificateImage, String legalPersonFrontImage, String legalPersonBackImage, String qualificationsImage, String creditReportImage, String customer_no) {
		EnterpriseEntity enterprise = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		if (AuditStateEnum.PASS == enterprise.getAuditState()) {
			throw new BusinessException("企业已经审核通过");
		}
		enterprise.setBusinessLicenceImage(businessLicenceImage);
		enterprise.setCertificateImage(certificateImage);
		enterprise.setLegalPersonBackImage(legalPersonBackImage);
		enterprise.setLegalPersonFrontImage(legalPersonFrontImage);
		enterprise.setQualificationsImage(qualificationsImage);
		enterprise.setCertificateImage(certificateImage);
		enterprise.setCreditReportImage(creditReportImage);
		enterprise.setAuditState(AuditStateEnum.UNAUDIT);
		enterprise.setSubmitState(Boolean.TRUE);
		enterprise.setCallback(Boolean.FALSE);
		enterpriseService.persistEnterprise(enterprise);

		String url = ConfigPropertites.getProperties("finance.customerAdd.service");
		Map<String, String> params = new HashMap<>();
		params.put("enterprise_id", String.valueOf(enterprise.getEnterpriseId()));
		params.put("tenant_id", String.valueOf(enterprise.getTenantId()));
		params.put("account_id", String.valueOf(enterprise.getAccountId()));
		params.put("enterprise_short_name", String.valueOf(enterprise.getEnterpriseShortName()));
		params.put("enterprise_name", String.valueOf(enterprise.getEnterpriseShortName()));
		params.put("nature", String.valueOf(enterprise.getNature()));
		params.put("business_type", String.valueOf(enterprise.getBusinessType()));
		params.put("qualifications", String.valueOf(enterprise.getQualifications()));
		params.put("business_licence", String.valueOf(enterprise.getBusinessLicence()));
		params.put("certificate", String.valueOf(enterprise.getCertificate()));
		params.put("address", String.valueOf(enterprise.getAddress()));
		params.put("contact_address", String.valueOf(enterprise.getContactAddress()));
		params.put("contact_number", String.valueOf(enterprise.getContactNumber()));
		params.put("business_scope", String.valueOf(enterprise.getBusinessScope()));
		params.put("registered_capital", String.valueOf(enterprise.getRegisteredCapital()));
		params.put("business_time_limit", String.valueOf(enterprise.getBusinessTimeLimit()));
		params.put("legal_person", String.valueOf(enterprise.getLegalPerson()));
		params.put("legal_idcard", String.valueOf(enterprise.getLegalIdcard()));
		params.put("legal_period", String.valueOf(enterprise.getLegalPeriod()));
		params.put("legal_duty", String.valueOf(enterprise.getLegalDuty()));
		params.put("zip_code", String.valueOf(enterprise.getZipCode()));
		params.put("procurator", String.valueOf(enterprise.getProcurator()));
		params.put("procurator_idcard", String.valueOf(enterprise.getProcuratorIdcard()));
		params.put("procurator_period", String.valueOf(enterprise.getProcuratorPeriod()));
		params.put("procurator_duty", String.valueOf(enterprise.getProcuratorDuty()));
		params.put("office_phone", String.valueOf(enterprise.getOfficePhone()));
		params.put("mobile", String.valueOf(enterprise.getMobile()));
		params.put("fax", String.valueOf(enterprise.getFax()));
		params.put("e_mail", String.valueOf(enterprise.geteMail()));
		params.put("deposit_bank", String.valueOf(enterprise.getDepositBank()));
		params.put("account_holder", String.valueOf(enterprise.getAccountHolder()));
		params.put("credit_card", String.valueOf(enterprise.getCreditCard()));
		params.put("remark", String.valueOf(enterprise.getRemark()));
		params.put("state", String.valueOf("有效"));
		params.put("audit_state", String.valueOf("未审核"));
		params.put("business_licence_image", String.valueOf("http://www.zjjr56.com/api/v1.0/downloadFile.file?fileUuid=" + enterprise.getBusinessLicenceImage()));
		params.put("certificate_image", String.valueOf("http://www.zjjr56.com/api/v1.0/downloadFile.file?fileUuid=" + enterprise.getCertificateImage()));
		params.put("legal_person_front_image", String.valueOf("http://www.zjjr56.com/api/v1.0/downloadFile.file?fileUuid=" + enterprise.getLegalPersonFrontImage()));
		params.put("legal_person_back_image", String.valueOf("http://www.zjjr56.com/api/v1.0/downloadFile.file?fileUuid=" + enterprise.getLegalPersonBackImage()));
		params.put("qualifications_image", String.valueOf("http://www.zjjr56.com/api/v1.0/downloadFile.file?fileUuid=" + enterprise.getQualificationsImage()));
		params.put("credit_report_image", String.valueOf("http://www.zjjr56.com/api/v1.0/downloadFile.file?fileUuid=" + enterprise.getCreditReportImage()));
		params.put("submit_state", String.valueOf("已提交"));
		params.put("enabled", String.valueOf("有效"));
		params.put("create_dt", String.valueOf(enterprise.getCreateDateTime()));
		params.put("update_dt", String.valueOf(enterprise.getUpdateDateTime()));
		params.put("forbidden", String.valueOf(enterprise.getForbidden()));
		params.put("freeze", String.valueOf(enterprise.getFreeze()));
		params.put("belongs_enterprise_code", String.valueOf(enterprise.getBelongsEnterpriseCode()));
		params.put("province", String.valueOf(enterprise.getProvince()));
		params.put("city", String.valueOf(enterprise.getCity()));

		params.put("district", String.valueOf(enterprise.getDistrict()));
		params.put("customer_no", String.valueOf(customer_no));
		if (null == enterprise.getEnterpriseType() || EnterpriseTypeEnum.CUSTOMER == enterprise.getEnterpriseType()) {
			params.put("enterprise_type", String.valueOf("普通客户"));
		} else {
			params.put("enterprise_type", String.valueOf("分销商"));
		}
		params.put("city", String.valueOf(enterprise.getCity()));

		String responseText = HttpClientHelper.post(url, params);
		logger.info("wenwenlong----------------"+responseText);
		System.out.println(responseText);
	}

	@Override
	@Transactional
	public String createEnterprise(EnterpriseBaseInfo enterpriseBaseInfo) {
		EnterpriseEntity enterprise = enterpriseService.inquireTenantEnterprise(FinanceSessionContext.getAccountTenantId(), true, Boolean.TRUE);
		EnterpriseEntity entity = EnterpriseCastor.fromEnterpriseBaseInfo(enterpriseBaseInfo, enterprise);
		if (FinanceSessionContext.getAppKey().equals(FinanceConstant.APPKEY_ENTERPRISE_IOS) || FinanceSessionContext.getAppKey().equals(FinanceConstant.APPKEY_ENTERPRISE_ANDROID)) {
			entity.setSubmitState(Boolean.TRUE);
		} else {
			entity.setSubmitState(Boolean.FALSE);
		}
		//		if (entity.getSubmitState() != null && entity.getSubmitState()) {
		//			throw new BusinessException("资质认证已经提交，不能修改！");
		//		}
		enterpriseService.createEnterprise(entity);
		EnterpriseCodeEntity enterpriseCode = enterpriseCodeService.inquireEnterpriseCodeDetail(null, entity.getEnterpriseId());
		if (enterpriseCode == null) {
			enterpriseCode = new EnterpriseCodeEntity();
			enterpriseCode.setEnterpriseId(entity.getEnterpriseId());
			DistrictInfoEntity districtInfo = null;
			if (enterpriseBaseInfo.getProvince().contains("辽宁") || enterpriseBaseInfo.getProvince().contains("吉林") || enterpriseBaseInfo.getProvince().contains("黑龙江")) {
				districtInfo = districtInfoService.inquireDistrictInfo(1L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(1L);
					districtInfo.setDistrictCode(10001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("河北") || enterpriseBaseInfo.getProvince().contains("天津") || enterpriseBaseInfo.getProvince().contains("山西") || enterpriseBaseInfo.getProvince().contains("内蒙")) {
				districtInfo = districtInfoService.inquireDistrictInfo(2L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(2L);
					districtInfo.setDistrictCode(20001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("江苏") || enterpriseBaseInfo.getProvince().contains("上海") || enterpriseBaseInfo.getProvince().contains("安徽") || enterpriseBaseInfo.getProvince().contains("江西") || enterpriseBaseInfo.getProvince().contains("四川") || enterpriseBaseInfo.getProvince().contains("重庆")) {
				districtInfo = districtInfoService.inquireDistrictInfo(3L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(3L);
					districtInfo.setDistrictCode(30001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("广东")) {
				districtInfo = districtInfoService.inquireDistrictInfo(4L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(4L);
					districtInfo.setDistrictCode(40001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("浙江") || enterpriseBaseInfo.getProvince().contains("福建")) {
				districtInfo = districtInfoService.inquireDistrictInfo(5L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(5L);
					districtInfo.setDistrictCode(50001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("广西") || enterpriseBaseInfo.getProvince().contains("海南")) {
				districtInfo = districtInfoService.inquireDistrictInfo(6L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(6L);
					districtInfo.setDistrictCode(60001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else if (enterpriseBaseInfo.getProvince().contains("山东")) {
				districtInfo = districtInfoService.inquireDistrictInfo(7L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(7L);
					districtInfo.setDistrictCode(70001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			} else {
				districtInfo = districtInfoService.inquireDistrictInfo(8L);
				if (districtInfo == null) {
					districtInfo = new DistrictInfoEntity();
					districtInfo.setDistrictId(8L);
					districtInfo.setDistrictCode(00001L);
					districtInfoService.createDistrictInfo(districtInfo);
				} else {
					districtInfo.setDistrictCode(districtInfo.getDistrictCode() + 1L);
				}
			}

			districtInfoService.updateDistrictInfo(districtInfo);
			enterpriseCode.setEnterpriseCode(String.valueOf(districtInfo.getDistrictCode()));
			enterpriseCodeService.createEnterpriseCode(enterpriseCode);
		} else {
			enterpriseCode.setEnterpriseId(entity.getEnterpriseId());
			enterpriseCodeService.createEnterpriseCode(enterpriseCode);
		}
		return String.valueOf(entity.getEnterpriseId());
	}
		
	@Override
	@Transactional
	public String createEnterpriseQualification(String unitTypeId, Long enterpriseId, String scardType, String enterpriseName,
			String codeUSC, String certificate, String businessLicence, String address, String contactAddress,
			String businessScope, String registeredCapital, String businessTimeLimit, String enterpriseType,
			String province, String city, String district, String businessType, String belongsEnterpriseCode,
			String proxySaleCode, String sUserType, String legalPerson, String legalIdcard, String legalPeriod,
			String legalArea, String procurator, String procuratorIdcard, String procuratorPeriod, String creditCard,
			String accountHolder, String depositBank, String subbranch) {
		
		EnterpriseModifyEntity ee = new EnterpriseModifyEntity();
			Date date = new Date(); 
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
			String dateTime =dateFormat.format(date); 
			ParsePosition pos = new ParsePosition(0);
			Date createDateTime = dateFormat.parse(dateTime, pos);
			String priseName=enterpriseName.replace("（", "(").replace("）", ")");
			ee.setUnitTypeId(unitTypeId);//单位类型
			ee.setEnterpriseId(enterpriseId);
			ee.setState(StateEnum.UNKNOWN);
			ee.setScardType(scardType);//证件类型
			ee.setEnterpriseName(priseName);//企业名称
			ee.setCreateDateTime(createDateTime);//修改时间
			if(!"".equals(codeUSC)){
				ee.setCodeUSC(codeUSC);//统一社会代码
			}
			if(!"".equals(certificate)){
				ee.setCertificate(certificate);//组织机构代码
			}
			if(!"".equals(businessLicence)){
				ee.setBusinessLicence(businessLicence);//营业执照
			}       
			ee.setAddress(address);//营业执照所在地
			ee.setContactAddress(contactAddress);//联系地址
			ee.setBusinessScope(businessScope);//经营范围
			ee.setRegisteredCapital(registeredCapital);//注册资金
			ee.setBusinessTimeLimit(businessTimeLimit);//营业期限
			if("0".equals(enterpriseType)){
				ee.setEnterpriseType(EnterpriseTypeEnum.CUSTOMER);//客户
			}else{
				ee.setEnterpriseType(EnterpriseTypeEnum.DISTRIBUTORS);//分销商
			}
			ee.setProvince(province);//企业所在省
			ee.setCity(city);//企业所在市
			ee.setDistrict(district);//区
			ee.setBusinessType(businessType);//经营类型
			if(!"".equals(belongsEnterpriseCode)){
				ee.setBelongsEnterpriseCode(belongsEnterpriseCode);//客户邀请码
			}   
			if(!"".equals(procuratorPeriod)){
				ee.setProcurator(procuratorPeriod);//代销码
			}   
			ee.setsUserType(sUserType);//填写人身份
			ee.setLegalPerson(legalPerson);//法人姓名
			ee.setLegalIdcard(legalIdcard);//法人身份证号
			ee.setLegalArea(legalArea);//法定代表人归属地
			if(!"".equals(procurator)){
				ee.setProcurator(procurator);//代理人姓名
			}
			if(!"".equals(procuratorIdcard)){
				ee.setProcuratorIdcard(procuratorIdcard);//代理人身份证号
			}
			if(!"".equals(procuratorPeriod)){
				ee.setProcuratorPeriod(procuratorPeriod);//procuratorPeriod
			}
			ee.setCreditCard(creditCard.replaceAll(" ", ""));//企业对公银行账户
			ee.setAccountHolder(accountHolder);//开户名
			ee.setDepositBank(depositBank);//开户行名称
			ee.setSubbranch(subbranch);//银行开户支行
			PersistUtil.insert(ee);
			logger.info("ee----------------"+ee);
			
			return String.valueOf(ee.getAuthenticationId());
	}
	

	@Transactional
	@Override
	public void updateEnterprise(EnterpriseBaseDetail enterpriseBaseDetail) {
		Long enterpriseId = FinanceSessionContext.getEnterpriseId();
		enterpriseBaseDetail.setEnterpriseId(enterpriseId);
		
		EnterpriseEntity entity = EnterpriseCastor.fromEnterpriseBaseInfo(enterpriseBaseDetail, null, "auditRemark");
		if (AuditStateEnum.PASS != entity.getAuditState() && AuditStateEnum.FINISH != entity.getAuditState()) {
			entity.setAuditState(AuditStateEnum.UNAUDIT);
		}
		if ("1".equals(entity.getScardType())) {
			entity.setCertificate("");
			entity.setRegNo("");
		} else if ("0".equals(entity.getScardType())) {
			entity.setCodeUSC("");
		}
		enterpriseService.updateEnterprise(entity);
	}

	@Override
	@Transactional
	public void submitEnterprise(Long enterpriseId) {
		
		EnterpriseEntity entity = null;
		if (null == enterpriseId) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		entity = enterpriseService.inquireEnterprise(enterpriseId);
		if (null == entity) {
			throw new BusinessException("找不到该企业");
		}
		
		EqbResult result = eqianbaoActionApi.informationCheck(entity.getEnterpriseId(), entity.getUnitTypeId(), entity.getScardType(), entity.getEnterpriseName(), entity.getRegNo(), entity.getProvince(), entity.getCity(), entity.getDistrict(), entity.getContactAddress(), entity.getBusinessTimeLimit(), entity.getCodeUSC(), entity.getCertificate(), entity.getsUserType(), entity.getLegalPerson(), entity.getLegalIdcard(), entity.getLegalArea(), entity.getProcurator(), entity.getProcuratorIdcard(), entity.getProcuratorPeriod(), entity.getCreditCard(), entity.getSubbranch(), entity.getDepositBank(), entity.getPrcptcd());
		logger.info(result.getErrorCode() + "=======================================================" + result.getMsg());
		if ("0".equals(result.getErrorCode())) {
			entity.setSubmitState(Boolean.TRUE);
			enterpriseService.updateEnterprise(entity);
		} else {
			throw new BusinessException(result.getMsg());
		}
	}
	
	@Override
	@Transactional
	public void submitEnterprisePlatform(Long enterpriseId, String creditCard, String prcptcd, String depositBank,
			String subbranch) {
		EnterpriseEntity entity = enterpriseService.inquireEnterprise(enterpriseId);
		entity.setCreditCard(creditCard);
		entity.setPrcptcd(prcptcd);
		entity.setDepositBank(depositBank);
		entity.setSubbranch(subbranch);
		enterpriseService.updateEnterprise(entity);
		
		EqbResult result = eqianbaoActionApi.informationCheck(entity.getEnterpriseId(), entity.getUnitTypeId(), entity.getScardType(), entity.getEnterpriseName(), entity.getRegNo(), entity.getProvince(), entity.getCity(), entity.getDistrict(), entity.getContactAddress(), entity.getBusinessTimeLimit(), entity.getCodeUSC(), entity.getCertificate(), entity.getsUserType(), entity.getLegalPerson(), entity.getLegalIdcard(), entity.getLegalArea(), entity.getProcurator(), entity.getProcuratorIdcard(), entity.getProcuratorPeriod(), entity.getCreditCard(), entity.getSubbranch(), entity.getDepositBank(), entity.getPrcptcd());
		logger.info(result.getErrorCode() + "=======================================================" + result.getMsg());
		if ("0".equals(result.getErrorCode())) {
			if (AuditStateEnum.PASS != entity.getAuditState() || AuditStateEnum.FINISH != entity.getAuditState()) {
				
			}
		}
	}
	
	@Override
	@Transactional
	public void submitAuthentication(Long authenticationId) {
		EnterpriseModifyEntity entity = null;
		if (null == authenticationId) {
			entity = enterpriseService.inquireAuthenticationEnterprises(FinanceSessionContext.getAccountTenantId(), true, Boolean.TRUE);
		} else {
			entity = enterpriseService.inquireAuthentication(authenticationId);
		}
		if (null == entity) {
			throw new BusinessException("找不到该企业");
		}
		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), "客户", 1L, "客户" + entity.getEnterpriseName() + "发起客户认证申请", entity.getAuthenticationId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		enterpriseService.updateAuthenticationEnterprise(entity);
		EnterpriseGradeEvaluationEntity evaluation = new EnterpriseGradeEvaluationEntity();
		evaluation.setEnterpriseId(entity.getEnterpriseId());
		enterpriseGradeEvaluationService.createEnterpriseGradeEvaluation(evaluation);

		String tmp = "客户(%s)已提交资质认证，请及时审批！";
		SendLetterMessage.sendLetterMessage("clientManageDetailAudit1_1", String.format(tmp, entity.getEnterpriseName()));
	}

	@Override
	public void updateEnterpriseInfo(Long enterpriseId, String officePhone, String fax, String eMail, String depositBank, String accountHolder, String creditCard) {
		EnterpriseEntity entity = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		entity.setOfficePhone(officePhone);
		entity.setFax(fax);
		entity.seteMail(eMail);
		entity.setDepositBank(depositBank);
		entity.setAccountHolder(accountHolder);
		entity.setCreditCard(creditCard);
		enterpriseService.persistEnterprise(entity);
	}

	@Transactional
	@Override
	public void supplementEnterpriseImage(Long enterpriseId, String businessLicenceImage, String certificateImage, String legalPersonFrontImage, String legalPersonBackImage, String qualificationsImage, String creditReportImage) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		if (AuditStateEnum.PASS == persistence.getAuditState()) {
			throw new BusinessException("企业已经审核通过");
		}
		persistence.setBusinessLicenceImage(businessLicenceImage);
		persistence.setCertificateImage(certificateImage);
		persistence.setLegalPersonBackImage(legalPersonBackImage);
		persistence.setLegalPersonFrontImage(legalPersonFrontImage);
		persistence.setQualificationsImage(qualificationsImage);
		persistence.setCertificateImage(certificateImage);
		persistence.setCreditReportImage(creditReportImage);
		persistence.setAuditState(AuditStateEnum.UNAUDIT);
		enterpriseService.persistEnterprise(persistence);
	}
	@Transactional
	@Override
	public void authenticationEnterpriseImage(Long authenticationId,String businessLicenceImage, String certificateImage,
			String legalPersonFrontImage, String legalPersonBackImage, String qualificationsImage,
			String creditReportImage) {
		EnterpriseModifyEntity persistence = enterpriseService.queryEnterpriseDetail(authenticationId);
		persistence.setBusinessLicenceImage(businessLicenceImage);
		persistence.setCertificateImage(certificateImage);
		persistence.setLegalPersonBackImage(legalPersonBackImage);
		persistence.setLegalPersonFrontImage(legalPersonFrontImage);
		persistence.setQualificationsImage(qualificationsImage);
		persistence.setCertificateImage(certificateImage);
		persistence.setCreditReportImage(creditReportImage);
		persistence.setAuditState(AuditStateEnum.UNAUDIT);
		enterpriseService.persistAuthenticationEnterprise(persistence);
		
	}
	@Override
	@Transactional
	public void saveEnterpriseAudit(Long enterpriseId, Integer auditType, Boolean auditState, String audit, String approvalBooks) {
		EnterpriseEntity entity = enterpriseService.inquireEnterprise(enterpriseId);
//		if (ApproveTypeEnum.EQB == entity.getApproveType() && AuthenticationEnum.ACSUCCESS != entity.getAuthentication()) {
//			throw new BusinessException("E签宝认证通过后才可继续审核！");
//		}
		entity.setCallback(Boolean.FALSE);
		switch (auditType) {
		case 1:
			if (entity.getAuditSubmitState1() != null && entity.getAuditSubmitState1()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit1(audit);
			entity.setAuditState1(auditState);
			entity.setAuditDate1(DateUtil.now());
			entity.setAuditor1(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId1(FinanceSessionContext.getAccountId());
			entity.setCallback(Boolean.FALSE);
			break;
		case 2:
			if (entity.getAuditSubmitState2() != null && entity.getAuditSubmitState2()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit2(audit);
			entity.setAuditState2(auditState);
			entity.setAuditDate2(DateUtil.now());
			entity.setAuditor2(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId2(FinanceSessionContext.getAccountId());
			break;
		case 3:
			if (entity.getAuditSubmitState3() != null && entity.getAuditSubmitState3()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit3(audit);
			entity.setAuditState3(auditState);
			entity.setAuditDate3(DateUtil.now());
			entity.setAuditor3(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId3(FinanceSessionContext.getAccountId());
			break;
		case 4:
			if (entity.getAuditSubmitState4() != null && entity.getAuditSubmitState4()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterpriseId);
			EnterpriseGradeEvaluationEntity egee = null;
			if (grade == null) {
				egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluation(enterpriseId);
			} else {
				egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(grade.getGradeEvaluationId());
			}
			egee.setApprovalBooks(approvalBooks);
			enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(egee);
			entity.setAudit4(audit);
			entity.setAuditState4(auditState);
			entity.setAuditDate4(DateUtil.now());
			entity.setAuditor4(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId4(FinanceSessionContext.getAccountId());
			break;
		case 5:
			if (entity.getAuditSubmitState5() != null && entity.getAuditSubmitState5()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit5(audit);
			entity.setAuditState5(auditState);
			entity.setAuditDate5(DateUtil.now());
			entity.setAuditor5(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId5(FinanceSessionContext.getAccountId());
			break;
		case 6:	
			if (entity.getAuditSubmitState6() != null && entity.getAuditSubmitState6()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit6(audit);
			entity.setAuditState6(auditState);
			entity.setAuditDate6(DateUtil.now());
			entity.setAuditor6(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId6(FinanceSessionContext.getAccountId());
			break;
		case 7:	
			if (entity.getAuditSubmitState7() != null && entity.getAuditSubmitState7()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit7(audit);
			entity.setAuditState7(auditState);
			entity.setAuditDate7(DateUtil.now());
			entity.setAuditor7(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId7(FinanceSessionContext.getAccountId());
			break;
		case 8:	
			if (entity.getAuditSubmitState8() != null && entity.getAuditSubmitState8()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit8(audit);
			entity.setAuditState8(auditState);
			entity.setAuditDate8(DateUtil.now());
			entity.setAuditor8(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId8(FinanceSessionContext.getAccountId());
			break;
		case 9:	
			if (entity.getAuditSubmitState9() != null && entity.getAuditSubmitState9()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit9(audit);
			entity.setAuditState9(auditState);
			entity.setAuditDate9(DateUtil.now());
			entity.setAuditor9(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId9(FinanceSessionContext.getAccountId());
			break;
		case 10:	
			if (entity.getAuditSubmitState10() != null && entity.getAuditSubmitState10()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit10(audit);
			entity.setAuditState10(auditState);
			entity.setAuditDate10(DateUtil.now());
			entity.setAuditor10(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId10(FinanceSessionContext.getAccountId());
			break;
		case 11:	
			if (entity.getAuditSubmitState11() != null && entity.getAuditSubmitState11()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit11(audit);
			entity.setAuditState11(auditState);
			entity.setAuditDate11(DateUtil.now());
			entity.setAuditor11(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId11(FinanceSessionContext.getAccountId());
			break;
		case 12:	
			if (entity.getAuditSubmitState12() != null && entity.getAuditSubmitState12()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit12(audit);
			entity.setAuditState12(auditState);
			entity.setAuditDate12(DateUtil.now());
			entity.setAuditor12(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId12(FinanceSessionContext.getAccountId());
			break;
		default:
			break;
		}
		enterpriseService.persistEnterprise(entity);
	}

	@Override
	@Transactional
	public void submitEnterpriseAudit(Long enterpriseId, Integer auditType, Boolean auditState, String audit, String approvalBooks) {
		//1-业务经理 7-业务总监 8-业务副总  2-风控审核 9-风控领导 10-副总经理 3-总经理 4-风控批复 12-董事长 5-市场部确认 6-计财部确认 11-运营部确认 
		saveEnterpriseAudit(enterpriseId, auditType, auditState, audit, approvalBooks);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		EnterpriseEntity entity = enterpriseService.inquireEnterprise(enterpriseId);
		FinanceAuditLogEntity fale = null;
		entity.setCallback(Boolean.FALSE);
		switch (auditType) {
		case 1:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "业务部:"+audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState1() == Boolean.TRUE) {
				entity.setAuditSubmitState1(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.YWZJ.getCode());

				SendLetterMessage.sendLetterMessage("clientManageDetailAudit7_1", String.format(tmp, entity.getEnterpriseName(), "业务总监审核"));
			} else {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				auditEnterpriseOppose(entity.getEnterpriseId(), null);
				initEnterprise(entity);
			}
			break;
		case 2:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "风控部:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState2() == Boolean.TRUE) {
				entity.setAuditSubmitState2(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit9_1", String.format(tmp, entity.getEnterpriseName(), "风控领导"));
			} else {
				initEnterprise(entity);
			}
			break;
		case 3:
			if (entity.getAuditState3() == Boolean.TRUE) {
				entity.setAuditSubmitState3(Boolean.TRUE);
//				entity.setFinalState(ApiFinanceStateEnum.ZXMANAGE.getCode());
//				SendLetterMessage.sendLetterMessage("clientManageDetailAudit12_1", String.format(tmp, entity.getEnterpriseName(), "董事长"));
				entity.setFinalState(ApiFinanceStateEnum.RFK.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit4_1", String.format(tmp, entity.getEnterpriseName(), "风控批复"));
				
				EnterpriseEntity enterprise = enterpriseService.inquireEnterpriseDetail(entity.getEnterpriseId());
				enterprise.setAuditState(AuditStateEnum.PASS);
				enterpriseService.updateEnterprise(enterprise);
				
				EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
				EnterpriseGradeEvaluationEntity egee = null;
				if (grade == null) {
					egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluation(enterpriseId);
				} else {
					egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(grade.getGradeEvaluationId());
				}
				egee.setEffectiveStartDate(DateUtil.todayInt());
				egee.setAuditState(AuditStateEnum.PASS);

				grade.setEffective(Boolean.TRUE);
				BeanUtils.copyProperties(egee, grade);
				grade.setCreditAlready(BigDecimal.ZERO);
				enterpriseGradeService.persistEnterpriseGrade(grade);
//				String msg = "尊敬的"+ entity.getLegalPerson() +":客户您好！您的综合授信额度申请已完成审批,综合授信额度：" + com.yuexunit.finance.common.util.StringUtils.parseMoney(",###,###.00", grade.getCreditLine().divide(new BigDecimal(10000), BigDecimal.ROUND_HALF_UP)) + "万元.收到短信通知请联系一润供应链客户经理协助您完成网上贷款申请工作，客服热线:021-6094 5016 【一润供应链管理（上海）有限公司】";
//				SendMsgUtil.sendMsg(enterprise.getMobile(), msg);
				FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(grade.getEnterpriseId(), "资质认证", "enterprise.audit.conset", grade.getCreditLine(), grade.getEffectiveStartDate(), grade.getEffectiveEndDate());
				//同步到CRM系统
				synchronousToCrm("", entity.getLegalPeriod(), entity.getMobile(), entity.getMobile(), "1");
			} else {
				entity.setAudit3("");
				entity.setAuditDate3(null);
				entity.setAuditState3(Boolean.TRUE);
				entity.setAuditor3(null);
				entity.setAuditorId3(null);
				entity.setAuditSubmitState3(Boolean.FALSE);

				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "总经理:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			break;
		case 4:
			if (entity.getAuditState4() == Boolean.TRUE) {
				entity.setAuditSubmitState4(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.SCCWYY.getCode());

				SendLetterMessage.sendLetterMessage("clientManageDetailAudit5_1", String.format(tmp, entity.getEnterpriseName(), "市场部确认"));
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit6_1", String.format(tmp, entity.getEnterpriseName(), "计财部确认"));
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit11_1", String.format(tmp, entity.getEnterpriseName(), "运营部确认"));

			} else {
				initEnterprise(entity);
			}
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "风控批复:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			break;
		case 5:
			entity.setAuditSubmitState5(Boolean.TRUE);
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "市场部确认:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditSubmitState6() == Boolean.TRUE && entity.getAuditSubmitState11() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YY.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.CWYY.getCode());
			}

			if (Boolean.TRUE == entity.getAuditSubmitState5() && Boolean.TRUE == entity.getAuditSubmitState6() && Boolean.TRUE == entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getEnterpriseId(), entity.getEnterpriseId(), ApiTypeEnum.QYYH.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), entity.getEnterpriseName(), entity.getLegalPerson());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 6:
			entity.setAuditSubmitState6(Boolean.TRUE);
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "计财部确认:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());

			if (entity.getAuditSubmitState5() == Boolean.TRUE && entity.getAuditSubmitState11() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YY.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit11_1", String.format(tmp, entity.getEnterpriseName(), "运营部确认"));
			} else if (entity.getAuditSubmitState5() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit5_1", String.format(tmp, entity.getEnterpriseName(), "计财部确认"));
			} else if (entity.getAuditSubmitState5() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.SCYY.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit5_1", String.format(tmp, entity.getEnterpriseName(), "计财部确认"));
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit11_1", String.format(tmp, entity.getEnterpriseName(), "运营部确认"));
			}

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getEnterpriseId(), entity.getEnterpriseId(), ApiTypeEnum.QYYH.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), entity.getEnterpriseName(), entity.getLegalPerson());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 7:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "业务总监:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState7() == Boolean.TRUE) {
				entity.setAuditSubmitState7(Boolean.TRUE);
//				entity.setFinalState(ApiFinanceStateEnum.YWFZ.getCode());
//				SendLetterMessage.sendLetterMessage("clientManageDetailAudit8_1", String.format(tmp, entity.getEnterpriseName(), "业务副总"));
				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit2_1", String.format(tmp, entity.getEnterpriseName(), "业务副总"));
			} else {
				initEnterprise(entity);
			}
			break;
		case 8:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState8() == Boolean.TRUE) {
				entity.setAuditSubmitState8(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit2_1", String.format(tmp, entity.getEnterpriseName(), "风控审核"));
			} else {
				initEnterprise(entity);
			}
			break;
		case 9:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "风控领导:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState9() == Boolean.TRUE) {
				entity.setAuditSubmitState9(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit10_1", String.format(tmp, entity.getEnterpriseName(), "副总经理"));
			} else {
				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit2("");
				entity.setAuditDate2(null);
				entity.setAuditState2(Boolean.TRUE);
				entity.setAuditor2(null);
				entity.setAuditorId2(null);
				entity.setAuditSubmitState2(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 10:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "副总经理:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState10() == Boolean.TRUE) {
				entity.setAuditSubmitState10(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.TMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit3_1", String.format(tmp, entity.getEnterpriseName(), "总经理"));
			} else {
				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 11:
			entity.setAuditSubmitState11(Boolean.TRUE);
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "运营部确认:" + audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			//			entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			if (entity.getAuditSubmitState6() == Boolean.TRUE && entity.getAuditSubmitState5() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.RYW.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit5_1", String.format(tmp, entity.getEnterpriseName(), "运营部确认"));
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState5() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit6_1", String.format(tmp, entity.getEnterpriseName(), "计财部确认"));
			} else if (entity.getAuditSubmitState6() == Boolean.FALSE && entity.getAuditSubmitState5() == Boolean.FALSE) {
				entity.setFinalState(ApiFinanceStateEnum.SCCW.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit6_1", String.format(tmp, entity.getEnterpriseName(), "计财部确认"));
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit5_1", String.format(tmp, entity.getEnterpriseName(), "运营部确认"));
			}

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getEnterpriseId(), entity.getEnterpriseId(), ApiTypeEnum.QYYH.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), entity.getEnterpriseName(), entity.getLegalPerson());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 12:
			if (entity.getAuditState12() == Boolean.TRUE) {
				entity.setAuditSubmitState12(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.RFK.getCode());
				SendLetterMessage.sendLetterMessage("clientManageDetailAudit4_1", String.format(tmp, entity.getEnterpriseName(), "风控批复"));
			
				EnterpriseEntity enterprise = enterpriseService.inquireEnterpriseDetail(entity.getEnterpriseId());
				enterprise.setAuditState(AuditStateEnum.PASS);
				enterpriseService.updateEnterprise(enterprise);
				
				EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(enterprise.getEnterpriseId());
				EnterpriseGradeEvaluationEntity egee = null;
				if (grade == null) {
					egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluation(enterpriseId);
				} else {
					egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(grade.getGradeEvaluationId());
				}
				egee.setEffectiveStartDate(DateUtil.todayInt());
				egee.setAuditState(AuditStateEnum.PASS);

				grade.setEffective(Boolean.TRUE);
				BeanUtils.copyProperties(egee, grade);
				grade.setCreditAlready(BigDecimal.ZERO);
				enterpriseGradeService.persistEnterpriseGrade(grade);
				String msg = "尊敬的"+ entity.getLegalPerson() +":客户您好！您的综合授信额度申请已完成审批,综合授信额度：" + com.yuexunit.finance.common.util.StringUtils.parseMoney(",###,###.00", grade.getCreditLine().divide(new BigDecimal(10000), BigDecimal.ROUND_HALF_UP)) + "万元.收到短信通知请联系一润供应链客户经理协助您完成网上贷款申请工作，客服热线:021-6094 5016 【一润供应链管理（上海）有限公司】";
				SendMsgUtil.sendMsg(enterprise.getMobile(), msg);
				FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(grade.getEnterpriseId(), "资质认证", "enterprise.audit.conset", grade.getCreditLine(), grade.getEffectiveStartDate(), grade.getEffectiveEndDate());
				//同步到CRM系统
				synchronousToCrm("", entity.getLegalPeriod(), entity.getMobile(), entity.getMobile(), "1");
			} else {
				
				entity.setAudit3("");
				entity.setAuditDate3(null);
				entity.setAuditState3(Boolean.TRUE);
				entity.setAuditor3(null);
				entity.setAuditorId3(null);
				entity.setAuditSubmitState3(Boolean.FALSE);

				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);
				
				entity.setAudit12("");
				entity.setAuditDate12(null);
				entity.setAuditState12(Boolean.TRUE);
				entity.setAuditor12(null);
				entity.setAuditorId12(null);
				entity.setAuditSubmitState12(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			break;
		default:
			break;
		}
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		enterpriseService.persistEnterprise(entity);
	}

	@Override
	@Transactional
	public void transferToEnterprise(String enterpriseName, String address, String name, String mobile,
			String accountName, String is_inside) {

		logger.info("enterpriseName:" + enterpriseName);
		logger.info("address:" + address);
		logger.info("name:" + name);
		logger.info("mobile:" + mobile);
		logger.info("accountName:" + accountName);
		logger.info("is_inside:" + is_inside);
		
		if (StringUtils.isBlank(accountName)) {
			throw new BusinessException("账户名不能为空");
		}

		//		AccountId account = accountAction.inquireAccountIdByAlias(mobile[i], AccountNameType.MOBILE.ordinal());
		AccountNameEntity ane = accountService.inquireAccountName(accountName);
		if (ane != null) {
			throw new BusinessException("该账号已存在");
		}

		if ("0".equals(is_inside)) {
			CreateEmployee ce = new CreateEmployee();
			ce.setCurrentArea("-");
			ce.setGender(0);
			ce.setName(name);
			ce.setMobile(mobile);
			ce.setEmpCode(mobile);
			organizationActionApi.createEmployee(ce);
		} else if ("1".equals(is_inside)) {
			Long accountId = accountAction.createAccountSimple(mobile, "123456");
//			AccountAlias accountAlias = new AccountAlias();
//			accountAlias.setAccountId(accountId);
//			accountAlias.setAccountName(mobile);
//			accountAlias.setType(AccountNameType.MOBILE);
//			accountAction.updateAccountAlias(accountAlias);
			
			ane = accountService.inquireAccountName(mobile);
			if (ane == null) {
				ane = new AccountNameEntity();
				ane.setAccountId(accountId);
				ane.setType(AccountNameType.MOBILE);
				ane.setAccountName(mobile);
				PersistUtil.insert(ane);
			} else {
				ane.setType(AccountNameType.MOBILE);
				ane.setAccountName(mobile);
				PersistUtil.update(ane);
			}
			
			// 创建租户信息
			TenantIdOutput output = tenantAction.createTenantByAccountId(accountId, null);

			EnterpriseEntity enterprise = new EnterpriseEntity();
			initEnterprise(enterprise);
			enterprise.setTenantId(output.getTenantId());
			enterprise.setEnterpriseName(enterpriseName);
			enterprise.setAddress(address);
			enterprise.setLegalPerson(name);
			enterprise.setMobile(mobile);
			enterprise.setAccountId(accountId);
			enterprise.setCallback(Boolean.FALSE);
			enterpriseService.createEnterprise(enterprise);
		}
	}

	@Override
	public void synchronousToCrm(String address, String name, String mobile, String accountName, String is_inside) {
		String url = ConfigPropertites.getProperties("finance.saveUser.service");
		Map<String, String> params = new HashMap<>();
		params.put("user_id", "5b51ff2385d344b7b8bc3b09767487d9");
		params.put("address", address);
		params.put("name", name);
		params.put("mobile", mobile);
		params.put("accountName", accountName);
		params.put("is_inside", is_inside);
		System.out.println(url);
		System.out.println(params);
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		logger.info(responseText);
	}

	private void initEnterprise(EnterpriseEntity entity) {
		entity.setAudit1("");
		entity.setAudit2("");
		entity.setAudit3("");
		entity.setAudit4("");
		entity.setAudit5("");
		entity.setAudit6("");
		entity.setAudit7("");
		entity.setAudit8("");
		entity.setAudit9("");
		entity.setAudit10("");
		entity.setAudit11("");
		entity.setAudit12("");
		entity.setAuditDate1(null);
		entity.setAuditDate2(null);
		entity.setAuditDate3(null);
		entity.setAuditDate4(null);
		entity.setAuditDate5(null);
		entity.setAuditDate6(null);
		entity.setAuditDate7(null);
		entity.setAuditDate8(null);
		entity.setAuditDate9(null);
		entity.setAuditDate10(null);
		entity.setAuditDate11(null);
		entity.setAuditDate12(null);
		entity.setAuditState1(Boolean.TRUE);
		entity.setAuditState2(Boolean.TRUE);
		entity.setAuditState3(Boolean.TRUE);
		entity.setAuditState4(Boolean.TRUE);
		entity.setAuditState5(Boolean.TRUE);
		entity.setAuditState6(Boolean.TRUE);
		entity.setAuditState7(Boolean.TRUE);
		entity.setAuditState8(Boolean.TRUE);
		entity.setAuditState9(Boolean.TRUE);
		entity.setAuditState10(Boolean.TRUE);
		entity.setAuditState11(Boolean.TRUE);
		entity.setAuditState12(Boolean.TRUE);
		entity.setAuditor1(null);
		entity.setAuditor2(null);
		entity.setAuditor3(null);
		entity.setAuditor4(null);
		entity.setAuditor5(null);
		entity.setAuditor6(null);
		entity.setAuditor7(null);
		entity.setAuditor8(null);
		entity.setAuditor9(null);
		entity.setAuditor10(null);
		entity.setAuditor11(null);
		entity.setAuditorId1(null);
		entity.setAuditorId2(null);
		entity.setAuditorId3(null);
		entity.setAuditorId4(null);
		entity.setAuditorId5(null);
		entity.setAuditorId6(null);
		entity.setAuditorId7(null);
		entity.setAuditorId8(null);
		entity.setAuditorId9(null);
		entity.setAuditorId10(null);
		entity.setAuditorId11(null);
		entity.setAuditorId12(null);
		entity.setAuditSubmitState1(Boolean.FALSE);
		entity.setAuditSubmitState2(Boolean.FALSE);
		entity.setAuditSubmitState3(Boolean.FALSE);
		entity.setAuditSubmitState4(Boolean.FALSE);
		entity.setAuditSubmitState5(Boolean.FALSE);
		entity.setAuditSubmitState6(Boolean.FALSE);
		entity.setAuditSubmitState7(Boolean.FALSE);
		entity.setAuditSubmitState8(Boolean.FALSE);
		entity.setAuditSubmitState9(Boolean.FALSE);
		entity.setAuditSubmitState10(Boolean.FALSE);
		entity.setAuditSubmitState11(Boolean.FALSE);
		entity.setAuditSubmitState12(Boolean.FALSE);
		entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
		entity.setCallback(Boolean.TRUE);
	}

	@Transactional
	@Override
	public void auditEnterpriseConsent(EnterpriseGradeEvaluation params) {
		EnterpriseEntity enterprise = enterpriseService.inquireEnterpriseDetail(params.getEnterpriseId());
		enterprise.setAuditState(AuditStateEnum.PASS);
		enterpriseService.updateEnterprise(enterprise);

		EnterpriseGradeEvaluationEntity evaluation = EnterpriseCastor.fromEnterpriseGradeEvaluation(params);
		evaluation.setEffectiveStartDate(DateUtil.todayInt());
		evaluation.setAuditState(AuditStateEnum.PASS);
		if (evaluation.getGradeEvaluationId() == null || evaluation.getGradeEvaluationId() == 0L) {
			enterpriseGradeEvaluationService.createEnterpriseGradeEvaluation(evaluation);
		} else {
			enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(evaluation);
		}

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(params.getEnterpriseId());
		if (grade == null) {
			grade = new EnterpriseGradeEntity();
			grade.setEffective(Boolean.TRUE);
			BeanUtils.copyProperties(evaluation, grade);
			grade.setCreditAlready(BigDecimal.ZERO);
			enterpriseGradeService.createEnterpriseGrade(grade);
		} else {
			grade.setEffective(Boolean.TRUE);
			BeanUtils.copyProperties(evaluation, grade);
			grade.setCreditAlready(BigDecimal.ZERO);
			enterpriseGradeService.persistEnterpriseGrade(grade);
		}
//		SendMsgUtil.sendMsg(enterprise.getMobile(), "综合授信额度为:" + params.getCreditLine() + ",有效期为" + params.getEffectiveStartDate() + "-" + params.getEffectiveEndDate());
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(params.getEnterpriseId(), "资质认证", "enterprise.audit.conset", params.getCreditLine(), params.getEffectiveStartDate(), params.getEffectiveEndDate());
	}

	@Transactional
	@Override
	public void auditEnterpriseSave(EnterpriseGradeEvaluation params) {
		EnterpriseGradeEvaluationEntity evaluation = EnterpriseCastor.fromEnterpriseGradeEvaluation(params);
		evaluation.setEffectiveStartDate(DateUtil.todayInt());
		evaluation.setAuditState(AuditStateEnum.PASS);
		EnterpriseEntity ee = enterpriseService.inquireEnterprise(params.getEnterpriseId());
		if (null != params.getApproveType()) {
			ee.setApproveType(ApproveTypeEnum.valueOf(params.getApproveType()));
			enterpriseService.updateEnterprise(ee);
		}
		
		if (evaluation.getGradeEvaluationId() == null || evaluation.getGradeEvaluationId() == 0L) {
			enterpriseGradeEvaluationService.createEnterpriseGradeEvaluation(evaluation);
		} else {
			enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(evaluation);
		}

		EnterpriseGradeEntity grade = enterpriseGradeService.inquireEnterpriseGrade(params.getEnterpriseId());
		if (grade == null) {
			grade = new EnterpriseGradeEntity();
			grade.setEffective(Boolean.FALSE);
			BeanUtils.copyProperties(evaluation, grade);
			grade.setCreditAlready(BigDecimal.ZERO);
			enterpriseGradeService.createEnterpriseGrade(grade);
		} else {
			grade.setEffective(Boolean.FALSE);
			BeanUtils.copyProperties(evaluation, grade);
			grade.setCreditAlready(BigDecimal.ZERO);
			enterpriseGradeService.persistEnterpriseGrade(grade);
		}

		if (params.getBulkstockInfoIds() != null) {
			for(int i = 0; i < params.getBulkstockInfoIds().length; i++) {
				FinanceBulkstockPledgeRateEntity exist = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(evaluation.getGradeEvaluationId(), params.getBulkstockInfoIds()[i], ProductTypeEnum.valueOf(params.getProductType()[i]));
				BulkstockInfoEntity bie = bulkstockInfoService.inquireBulkstockInfo(params.getBulkstockInfoIds()[i]);
				if (exist != null) {
					throw new BusinessException("货物" + bie.getBulkstockName() + "(" + bie.getSpecificationName() + ")" + "在有效期内已设置过质押率！");
				}
				FinanceBulkstockPledgeRateEntity entity = new FinanceBulkstockPledgeRateEntity();
				entity.setGradeEvaluationId(evaluation.getGradeEvaluationId());
				entity.setBulkstockInfoId(params.getBulkstockInfoIds()[i]);
				entity.setPledgeRateCeiling(params.getPledgeRateCeilings()[i]);
				entity.setLoanRateCeiling(params.getLoanRateCeilings()[i]);
				entity.setEffectiveEndDate(DateUtil.parseDateInt(params.getEffectiveEndDates()[i]));
				entity.setEffectiveStartDate(DateUtil.parseDateInt(params.getEffectiveStartDates()[i]));
				entity.setProductName(params.getProductName()[i]);
				entity.setProductType(ProductTypeEnum.valueOf(params.getProductType()[i]));
				entity.setBailRate(params.getBailRates()[i]);
				financeBulkstockPledgeRateService.createFinanceBulkstockPledgeRate(entity);
			}
		}
	}

	@Transactional
	@Override
	public void auditEnterpriseOppose(Long enterpriseId, String auditRemark) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		persistence.setAuditState(AuditStateEnum.REFUSE);
		persistence.setSubmitState(Boolean.FALSE);
		persistence.setAuditRemark(auditRemark);
		enterpriseService.persistEnterprise(persistence);
//		SendMsgUtil.sendMsg(persistence.getMobile(), "很遗憾,您本次申请授信额度没有通过平台审核,请完善个人及企业资料,提供有效证明再次审核。");
		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(enterpriseId, "资质认证", "enterprise.audit.oppose");
	}

	@Transactional
	@Override
	public void freezeEnterprise(Long enterpriseId) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		persistence.setState(StateEnum.DISABLED);
		enterpriseService.persistEnterprise(persistence);
	}

	@Transactional
	@Override
	public void recoverEnterprise(Long enterpriseId) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		persistence.setState(StateEnum.VALID);
		enterpriseService.persistEnterprise(persistence);
	}

	@Transactional
	@Override
	public void freezeEnterprise1(Long enterpriseId) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		persistence.setFreeze(Boolean.TRUE);
		enterpriseService.persistEnterprise(persistence);
	}

	@Transactional
	@Override
	public void forbidEnterprise(Long enterpriseId) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		AccountPasswordEntity accountPassword = PersistUtil.get(AccountPasswordEntity.class, persistence.getAccountId());
		accountPassword.setEnabled(Boolean.FALSE);
		PersistUtil.update(accountPassword);
		persistence.setForbidden(Boolean.TRUE);
		enterpriseService.persistEnterprise(persistence);
	}

	@Transactional
	@Override
	public void enableEnterprise(Long enterpriseId) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		persistence.setForbidden(Boolean.FALSE);
		persistence.setFreeze(Boolean.FALSE);
		enterpriseService.persistEnterprise(persistence);

		AccountPasswordEntity accountPassword = PersistUtil.get(AccountPasswordEntity.class, persistence.getAccountId());
		accountPassword.setEnabled(Boolean.TRUE);
		PersistUtil.update(accountPassword);
	}

	@Transactional
	@Override
	public void disableEnterprise(Long enterpriseId) {
		// 扣除 状态为 取消/审批不通过/已完成/已评价
		Set<FinanceStateEnum> financeStates = CollectionUtils.convertSet(FinanceStateEnum.values());
		financeStates.remove(FinanceStateEnum.CANCEL);
		financeStates.remove(FinanceStateEnum.APPROVE_NOPASS);
		financeStates.remove(FinanceStateEnum.FINISH);
		financeStates.remove(FinanceStateEnum.EVALUATE);

		List<FinanceApplicationEntity> list = financeApplicationService.inquireInProcessFinanceApplicationPageList(null, enterpriseId, null, financeStates, null);
		if (list.size() > 0) {
			throw new BusinessException("该企业用户下还有未完成的融资，不能删除该用户！");
		} else {
			enterpriseService.disableEnterprise(enterpriseId);
		}
	}

	@Transactional
	@Override
	public void updateEnterpriseShortName(Long enterpriseId, String enterpriseShortName) {
		EnterpriseEntity enterprise = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		enterprise.setEnterpriseShortName(enterpriseShortName);
		enterpriseService.persistEnterprise(enterprise);
	}

	@Override
	public EnterpriseDetail inquireEnterpriseDetail(Long enterpriseId) {
		EnterpriseEntity persistence = enterpriseService.inquireEnterpriseDetail(enterpriseId);
		return EnterpriseCastor.toEnterpriseDetail(persistence);
	}
	
	@Override
	public EnterpriseDetail queryEnterpriseModify(Long authenticationId) {//修改企业认证
		EnterpriseModifyEntity persistence = enterpriseService.inquireEnterpriseDetails(authenticationId);
		return EnterpriseCastor.toEnterpriseModify(persistence);
	}
	
	@Override
	public EnterpriseDetail queryAccountManagement(Long accountId) {//查询企业账户
		EnterpriseAccountEntity persistence = enterpriseService.inquireAccountManagements(accountId);
		return EnterpriseCastor.toEnterpriseAccounts(persistence);
	}
	
	@Override
	@Transactional
	public void modifyCertificationAudit(Long authenticationId) {
		EnterpriseModifyEntity persistence = enterpriseService.inquireEnterpriseDetails(authenticationId);
		long enterpriseId=persistence.getEnterpriseId();
		EnterpriseEntity ee = enterpriseService.inquireEnterprise(enterpriseId);
		ee.setScardType(persistence.getScardType());
		ee.setEnterpriseName(persistence.getEnterpriseName());
		ee.setCodeUSC(persistence.getCodeUSC());
		ee.setCertificate(persistence.getCertificate());
		ee.setBusinessLicence(persistence.getBusinessLicence());
		ee.setAddress(persistence.getAddress());
		ee.setContactAddress(persistence.getContactAddress());
		ee.setBusinessScope(persistence.getBusinessScope());
		ee.setRegisteredCapital(persistence.getRegisteredCapital());
		ee.setBusinessTimeLimit(persistence.getBusinessTimeLimit());
		ee.setEnterpriseType(persistence.getEnterpriseType());
		ee.setProvince(persistence.getProvince());
		ee.setCity(persistence.getCity());
		ee.setDistrict(persistence.getDistrict());
		ee.setBusinessType(persistence.getBusinessType());
		ee.setBelongsEnterpriseCode(persistence.getBelongsEnterpriseCode());
		ee.setProxySaleCode(persistence.getProxySaleCode());
		ee.setsUserType(persistence.getsUserType());
		ee.setLegalPerson(persistence.getLegalPerson());
		ee.setLegalIdcard(persistence.getLegalIdcard());
		ee.setLegalPeriod(persistence.getLegalPeriod());
		ee.setLegalArea(persistence.getLegalArea());
		ee.setProcurator(persistence.getProcurator());
		ee.setProcuratorIdcard(persistence.getProcuratorIdcard());
		ee.setProcuratorPeriod(persistence.getProcuratorPeriod());
		ee.setCreditCard(persistence.getCreditCard());
		ee.setAccountHolder(persistence.getAccountHolder());
		ee.setDepositBank(persistence.getDepositBank());
		ee.setSubbranch(persistence.getSubbranch());
		ee.setCreateDateTime(persistence.getCreateDateTime());
		persistence.setAuditState(AuditStateEnum.PASS);
		enterpriseService.updateAuthenticationEnterprise(persistence);
		enterpriseService.updateEnterprise(ee);
	}
	
	@Override
	@Transactional
	public void auditCertification(Long authenticationId) {
		EnterpriseModifyEntity persistence = enterpriseService.inquireEnterpriseDetails(authenticationId);
		persistence.setAuditState(AuditStateEnum.REFUSE);
		enterpriseService.updateAuthenticationEnterprise(persistence);
	}
	@Override
	public EnterpriseDetail inquireCurrentEnterpriseDetail() {
		EnterpriseEntity persistence = enterpriseService.inquireTenantEnterprise(FinanceSessionContext.getAccountTenantId(), false, Boolean.TRUE);
		return EnterpriseCastor.toEnterpriseDetail(persistence);
	}

	@Override
	public PageList<EnterpriseBaseDetail> inquireEnterprisePageList(String enterpriseName, Integer auditState,
			String mobile, String legalPerson, Integer state, String createDateTimeBegin, String createDateTimeEnd,
			Integer enterpriseType, Boolean isPassed, String followPerson, Integer productType, BigDecimal alreadyCreditStart, BigDecimal alreadyCreditEnd, Integer leftTime,
			Long finalState, PageCriteria page) {
		Date beginDateTime = DateUtils.formatBeginDay(createDateTimeBegin);
		Date endDateTime = DateUtils.formatEndDay(createDateTimeEnd);
		List<Long> enterpriseIds = null;
		List<Long> enterpriseId1 = null;
		List<Long> enterpriseId2 = null;
		if (StringUtil.isNotBlank(followPerson)) {
			enterpriseId1 = financeFollowPersonService.inquireFinanceFollowByfollowName(followPerson);
		}
		if (null != leftTime || alreadyCreditStart != null || alreadyCreditEnd != null) {
			enterpriseId2 = enterpriseGradeService.countEnterpriseByLeftTime(alreadyCreditStart, alreadyCreditEnd, leftTime);
		}
		if (enterpriseId1 != null || enterpriseId2 != null) {
			enterpriseIds = new ArrayList<>();
			if (enterpriseId1 != null) {
				enterpriseIds.addAll(enterpriseId1);
			}
			if (enterpriseId2 != null) {
				enterpriseIds.addAll(enterpriseId2);
			}
		}
		
		PageList<EnterpriseEntity> pages = enterpriseService.inquireEnterprisePageList(enterpriseIds, enterpriseName, AuditStateEnum.valueOf(auditState), mobile, legalPerson, StateEnum.valueOf(state), beginDateTime, endDateTime, EnterpriseTypeEnum.valueOf(enterpriseType), isPassed, finalState, page);
		PageList<EnterpriseBaseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseEntity entity : pages) {
			results.add(EnterpriseCastor.toEnterpriseBaseDetail(entity));
		}
		return results;
	}
	
	@Override
	public PageList<EnterpriseBaseDetail> queryBankCode(String dotName, PageCriteria page) {
		PageList<BankcodeEntity> pages = enterpriseService.queryBankCodeList(dotName,page);
		System.out.println("查出的银行数据共：\b"+pages.size()+"\b条");
		PageList<EnterpriseBaseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (BankcodeEntity entity : pages) {
			results.add(EnterpriseCastor.toBankcodeDetails(entity));
		}
		return results;
	}
	
	@Override
	public PageList<EnterpriseBaseDetail> queryEnterpriseModifyPageList(String enterpriseName, Integer auditState,
			String legalPerson, Integer state, String createDateTimeBegin, String createDateTimeEnd,
			Integer enterpriseType, Boolean isPassed, PageCriteria page) {
		Date beginDateTime = DateUtils.formatBeginDay(createDateTimeBegin);
		Date endDateTime = DateUtils.formatEndDay(createDateTimeEnd);
		PageList<EnterpriseModifyEntity> pages = enterpriseService.queryEnterpriseModifyPageList(enterpriseName, AuditStateEnum.valueOf(auditState),legalPerson,
				StateEnum.valueOf(state),beginDateTime,endDateTime, EnterpriseTypeEnum.valueOf(enterpriseType),isPassed, page);
		PageList<EnterpriseBaseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseModifyEntity entity : pages) {
			results.add(EnterpriseCastor.toEnterpriseBaseDetails(entity));
		}
		return results;
	}
	
	@Override
	public PageList<EnterpriseBaseDetail> queryAccountManagesPageList(String accountHolder,String depositBank, String createDateTimeBegin, String createDateTimeEnd, String subbranch,
			String creditCard,Integer defaultAccount, Long enterpriseId, PageCriteria page) {
		if (null == enterpriseId) {
			if (FinanceSessionContext.isEnterprise()) {
				enterpriseId = FinanceSessionContext.getEnterpriseId();
			}
		}
		Date beginDateTime = DateUtils.formatBeginDay(createDateTimeBegin);
		Date endDateTime = DateUtils.formatEndDay(createDateTimeEnd);
		PageList<EnterpriseAccountEntity> pages = enterpriseService.queryAccountManagesPageList(accountHolder, depositBank,
				beginDateTime,endDateTime,subbranch,creditCard,defaultAccount, enterpriseId, page);
		PageList<EnterpriseBaseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseAccountEntity entity : pages) {
			results.add(EnterpriseCastor.toAccountBaseDetails(entity));
		}
		return results;
	}
	
	@Override
	@Transactional
	public void topAccountInfo(Long accountId) {
		EnterpriseAccountEntity entity=enterpriseService.queryAccountInfoDetail(accountId);
        PageCriteria page = new PageCriteria();
        page.setPageIndex(1);
        page.setPageSize(20);
        PageList<EnterpriseAccountEntity> pages = enterpriseService.queryAccountManagesPageList(null, null,
				null,null,null,null,null,null, page);
		List<Object> lists=new ArrayList<Object>();
		for (EnterpriseAccountEntity entity2 : pages) {
			lists.add(entity2.getDefaultAccount().ordinal());
		}
		Set<Object> sets = new HashSet<Object>(lists);
		lists.clear();   
		lists.addAll(sets);
		if(lists ==null || lists.size() == 1){
			entity.setTop(Boolean.TRUE);
			entity.setDefaultAccount(DefaultAccountEnum.DEFAULT);	
		}
		enterpriseService.updateAccountInfos(entity);
	}
	@Override
	@Transactional
	public void cancelTopAccountInfo(Long accountId) {
		EnterpriseAccountEntity entity=enterpriseService.queryAccountInfoDetail(accountId);
	    PageCriteria page = new PageCriteria();
        page.setPageIndex(1);
        page.setPageSize(20);
        PageList<EnterpriseAccountEntity> pages = enterpriseService.queryAccountManagesPageList(null, null,
				null,null,null,null,null,null, page);
		List<Object> lists=new ArrayList<Object>();
		for (EnterpriseAccountEntity entity2 : pages) {
			lists.add(entity2.getDefaultAccount().ordinal());
		}
		Set<Object> sets = new HashSet<Object>(lists);
		lists.clear();   
		lists.addAll(sets);
		if(lists.size() == 2){
			entity.setTop(Boolean.FALSE);
			entity.setDefaultAccount(DefaultAccountEnum.UNKNOWN);
		}
		enterpriseService.updateAccountInfos(entity);
	}
	
	@Override
	public PageList<EnterpriseBaseDetail> queryEnterpriseModifyPageLists(String enterpriseName, Integer auditState,
			String legalPerson, Long enterpriseId, String createDateTimeBegin, String createDateTimeEnd,
			Integer enterpriseType, Boolean isPassed, PageCriteria page) {
		Date beginDateTime = DateUtils.formatBeginDay(createDateTimeBegin);
		Date endDateTime = DateUtils.formatEndDay(createDateTimeEnd);
		enterpriseId = enterpriseId == null ? FinanceSessionContext.getEnterpriseId() : enterpriseId;
		PageList<EnterpriseModifyEntity> pages = enterpriseService.queryEnterpriseModifyPageLists(enterpriseName, AuditStateEnum.valueOf(auditState),legalPerson,
				enterpriseId,beginDateTime,endDateTime, EnterpriseTypeEnum.valueOf(enterpriseType),isPassed, page);
		PageList<EnterpriseBaseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseModifyEntity entity : pages) {
			results.add(EnterpriseCastor.toEnterpriseBaseDetails(entity));
		}
		return results;
	}
	
	@Override
	public PageList<EnterpriseDetail> inquireFollowEnterprisePageList(PageCriteria page) {
		eIds.clear();
		PageList<EnterpriseEntity> pages = null;
		if (FinanceSessionContext.getAccountId() == 1L) {
			pages = enterpriseService.inquireEnterprisePageList(null, null, null, null, null, StateEnum.VALID, null, null, EnterpriseTypeEnum.DISTRIBUTORS, Boolean.TRUE, null, page);
		} else {
			FinanceEmployeeEntity ee = financeEmployeeService.inquireEmployeeByAccountId(FinanceSessionContext.getAccountId());
			if (ee == null) {
				throw new BusinessException("该员工不存在");
			}
			List<OrgREmpEntity> list = positionService.inquirePositionByUserId(1L, ee.getId());
			OrganizationEntity oe = organizationService.inquireOrganization(1L, list.get(0).getOrgId());
			if (oe.getName().contains("业务经理") || oe.getName().equals("驻外办")) {
				eIds.addAll(financeFollowPersonService.inquireFinanceFollowEnterpriseId(FinanceSessionContext.getAccountId()));
			} else {
				inquireOrgType(list.get(0).getOrgId());
			}

			pages = enterpriseService.inquireEnterprisePageListByIds(eIds.toArray(new Long[eIds.size()]), page);
		}

		if (pages == null) {
			return new PageList<>(PageCriteria.defaultInstance());
		}
		PageList<EnterpriseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseEntity entity : pages) {
			results.add(EnterpriseCastor.toEnterpriseDetail(entity));
		}
		return results;
	}

	private void inquireOrgType(Long orgId) {
		DetachedCriteria criteria = DetachedCriteria.forClass(OrganizationEntity.class);
		criteria.add(Restrictions.eq("parentId", orgId));
		List<OrganizationEntity> oes = PersistUtil.get(criteria);
		for (OrganizationEntity o : oes) {
			if (o.getName().contains("业务经理") || o.getName().equals("驻外办")) {
				DetachedCriteria criteria1 = DetachedCriteria.forClass(OrgREmpEntity.class);
				criteria1.add(Restrictions.eq("orgId", o.getId()));
				List<OrgREmpEntity> orees = PersistUtil.get(criteria1);
				for (OrgREmpEntity orgREmpEntity : orees) {
					FinanceEmployeeEntity employee = financeEmployeeService.inquireEmployee(orgREmpEntity.getEmpId());
					List<Long> ids = financeFollowPersonService.inquireFinanceFollowEnterpriseId(employee.getAccountId());
					eIds.addAll(ids);
				}
				return;
			} else {
				inquireOrgType(o.getId());
			}
		}
	}

	@Override
	public PageList<EnterpriseBaseDetail> inquireOwnEnterprisePageList(String enterpriseName, Integer auditState,
			String mobile, String legalPerson, Integer state, String createDateTimeBegin, String createDateTimeEnd,
			Integer enterpriseType, Long enterpriseId, Integer tradeType, PageCriteria page) {
		tradeType = tradeType == null ? 0 : tradeType;
		Date beginDateTime = DateUtils.formatBeginDay(createDateTimeBegin);
		Date endDateTime = DateUtils.formatEndDay(createDateTimeEnd);
		enterpriseId = enterpriseId == null ? FinanceSessionContext.getEnterpriseId() : enterpriseId;
		EnterpriseCodeEntity code = enterpriseCodeService.inquireEnterpriseCodeDetail(enterpriseId);
		List<Long> enterpriseIds1 = null;
		List<Long> enterpriseIds = enterpriseService.conutEnterpriseId(code.getEnterpriseCode());
		if (tradeType == 1) {
			enterpriseIds1 = new ArrayList<>();
			for (Long long1 : enterpriseIds) {
				FinanceApplicationEntity fae = financeApplicationService.inquireEnterpriseFinance(long1);
				if (fae == null) {
					enterpriseIds1.add(long1);
				}
			}
		} else {
			enterpriseIds1 = financeApplicationService.countEnterprise(enterpriseIds.toArray(new Long[enterpriseIds.size()]), tradeType);
		}
		PageList<EnterpriseEntity> pages = enterpriseService.inquireEnterprisePageList(enterpriseName, AuditStateEnum.valueOf(auditState), mobile, legalPerson, StateEnum.valueOf(state), beginDateTime, endDateTime, EnterpriseTypeEnum.valueOf(enterpriseType), code.getEnterpriseCode(), enterpriseIds1.toArray(new Long[enterpriseIds1.size()]), page);
		Integer totalRecordCount = pages.getTotalRecordCount();
		PageList<EnterpriseBaseDetail> results = new PageList<>(page, totalRecordCount);
		for (EnterpriseEntity entity : pages) {
			results.add(EnterpriseCastor.toEnterpriseBaseDetail(entity));
		}
		return results;
	}

	@Override
	public void initEnterpriseCode() {
		List<EnterpriseEntity> list = enterpriseService.inquireEnterpriseList(null);
		for (EnterpriseEntity enterpriseEntity : list) {
			EnterpriseCodeEntity code = enterpriseCodeService.inquireEnterpriseCodeDetail(enterpriseEntity.getEnterpriseId());
			if (code == null) {
				code = new EnterpriseCodeEntity();
				code.setEnterpriseId(enterpriseEntity.getEnterpriseId());
				code.setEnterpriseCode(SettingConstants.PRE_NUMBER_ENTERPRISE_CODE + RandomUtil.generateTimeNumber());
				enterpriseCodeService.createEnterpriseCode(code);
			} else {
				continue;
			}
		}

	}

	@Override
	public PageList<EnterpriseInfo> inquireEnterpriseListForSelector(String enterpriseName, Integer auditState, Integer state, Integer p, Integer s) {
		PageCriteria page = new PageCriteria();
		page.setPageIndex(p);
		page.setPageSize(s);
		PageList<EnterpriseEntity> pages = enterpriseService.inquireEnterprisePageList(null, enterpriseName, AuditStateEnum.valueOf(auditState), null, null, StateEnum.valueOf(state), null, null, null, null, null, page);
		PageList<EnterpriseInfo> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseEntity entity : pages) {
			EnterpriseInfo info = new EnterpriseInfo();
			info.setId(entity.getEnterpriseId());
			info.setName(entity.getEnterpriseName());
			results.add(info);
		}
		return results;
	}

	@Override
	public List<EnterpriseInfo> inquireEnterpriseList() {
		List<EnterpriseInfo> results = new ArrayList<>();
		List<EnterpriseEntity> pages = enterpriseService.inquireEnterpriseList(null);
		for (EnterpriseEntity entity : pages) {
			EnterpriseInfo info = new EnterpriseInfo();
			info.setId(entity.getEnterpriseId());
			info.setName(entity.getEnterpriseName());
			results.add(info);
		}
		return results;
	}

	// =====================================================================================================================================================//
	@Transactional
	@Override
	public String adjustEnterpriseGrade(EnterpriseGradeEvaluation params) {
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		if (StringUtils.isBlank(params.getEvaluationFileUuid())) {
			throw new BusinessException("评估表附件不允许为空");
		}
		EnterpriseGradeEvaluationEntity entity = EnterpriseCastor.fromEnterpriseGradeEvaluation(params);
		if (entity.getEffectiveStartDate() > entity.getEffectiveEndDate()) {
			throw new BusinessException("有效起始时间不能大于有效截止时间！");
		}
		entity.setAuditState(AuditStateEnum.UNAUDIT);
		entity.setAuditState1(Boolean.TRUE);
		entity.setAuditState2(Boolean.TRUE);
		entity.setAuditState3(Boolean.TRUE);
		entity.setAuditState4(Boolean.TRUE);
		entity.setAuditState5(Boolean.TRUE);
		entity.setAuditState6(Boolean.TRUE);
		entity.setAuditState7(Boolean.TRUE);
		entity.setAuditState8(Boolean.TRUE);
		entity.setAuditState9(Boolean.TRUE);
		entity.setAuditState10(Boolean.TRUE);
		entity.setAuditState11(Boolean.TRUE);
		entity.setAuditState12(Boolean.TRUE);
		entity.setAuditSubmitState1(Boolean.FALSE);
		entity.setAuditSubmitState2(Boolean.FALSE);
		entity.setAuditSubmitState3(Boolean.FALSE);
		entity.setAuditSubmitState4(Boolean.FALSE);
		entity.setAuditSubmitState5(Boolean.FALSE);
		entity.setAuditSubmitState6(Boolean.FALSE);
		entity.setAuditSubmitState7(Boolean.FALSE);
		entity.setAuditSubmitState8(Boolean.FALSE);
		entity.setAuditSubmitState9(Boolean.FALSE);
		entity.setAuditSubmitState10(Boolean.FALSE);
		entity.setAuditSubmitState11(Boolean.FALSE);
		entity.setAuditSubmitState12(Boolean.FALSE);
		entity.setCallback(Boolean.FALSE);
		entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
		entity.setAuditNumber(SettingConstants.PRE_AUDIT_NUMBER_ENTERPRISE + RandomUtil.generateTimeNumber());
		enterpriseGradeEvaluationService.createEnterpriseGradeEvaluation(entity);

		if (params.getBulkstockInfoIds() != null) {
			for(int i = 0; i < params.getBulkstockInfoIds().length; i++) {
				FinanceBulkstockPledgeRateEntity exist = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(entity.getGradeEvaluationId(), params.getBulkstockInfoIds()[i], ProductTypeEnum.valueOf(params.getProductType()[i]));
				BulkstockInfoEntity bie = bulkstockInfoService.inquireBulkstockInfo(params.getBulkstockInfoIds()[i]);
				if (exist != null) {
					throw new BusinessException("货物" + bie.getBulkstockName() + "(" + bie.getSpecificationName() + ")" + "在有效期内已设置过质押率！");
				}
				
				if (DateUtil.parseDateInt(params.getEffectiveEndDates()[i]) > entity.getEffectiveEndDate()) {
					throw new BusinessException("货物" + bie.getBulkstockName() + "(" + bie.getSpecificationName() + ")" + "的有效截止日期不能超过额度授信日期！");
				}
				
				FinanceBulkstockPledgeRateEntity fbpre = new FinanceBulkstockPledgeRateEntity();
				fbpre.setGradeEvaluationId(entity.getGradeEvaluationId());
				fbpre.setBulkstockInfoId(params.getBulkstockInfoIds()[i]);
				fbpre.setProductName(params.getProductName()[i]);
				fbpre.setProductType(ProductTypeEnum.valueOf(params.getProductType()[i]));
				fbpre.setPledgeRateCeiling(params.getPledgeRateCeilings()[i]);
				fbpre.setLoanRateCeiling(params.getLoanRateCeilings()[i]);
				fbpre.setEffectiveEndDate(DateUtil.parseDateInt(params.getEffectiveEndDates()[i]));
				fbpre.setEffectiveStartDate(DateUtil.parseDateInt(params.getEffectiveStartDates()[i]));
				fbpre.setBailRate(params.getBailRates()[i]);
				financeBulkstockPledgeRateService.createFinanceBulkstockPledgeRate(fbpre);
			}
		}

		if (params.getPledgeRateIds() != null && params.getPledgeRateIds().length > 0) {
			for (Long pledgeRateId : params.getPledgeRateIds()) {
				FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(pledgeRateId);
				FinanceBulkstockPledgeRateEntity nfbpre = new FinanceBulkstockPledgeRateEntity();
				BeanUtils.copyProperties(fbpre, nfbpre);
				nfbpre.setGradeEvaluationId(entity.getGradeEvaluationId());
				nfbpre.setPledgeRateId(null);
				financeBulkstockPledgeRateService.createFinanceBulkstockPledgeRate(nfbpre);
			}
		}

		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), 1L, FinanceSessionContext.getAccountFullName() + "发起客户等级调整", entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(entity.getEnterpriseId());
		String tmp = "客户(%s)有新的等级调整，请及时审批！";
		SendLetterMessage.sendLetterMessage("enterpriseManageAudit1_1", String.format(tmp, enterprise.getEnterpriseName()));

		return entity.getGradeEvaluationId().toString();
	}

	@Override
	public EnterpriseGradeEvaluationDetail inquireEnterpriseGradeEvaluationDetail(Long gradeEvaluationId) {
		EnterpriseGradeEvaluationEntity entity = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId);
		return EnterpriseCastor.toEnterpriseGradeEvaluationDetail(entity);
	}
	

	@Override
	public Boolean inquireExistEnterpriseGradeEvaluation(Long enterpriseId) {
//		List<EnterpriseGradeEvaluationEntity> egees = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationList(enterpriseId, 1);
//		if (egees != null && egees.size() > 0) {
//			return Boolean.TRUE;
//		}
//		return Boolean.FALSE;
		
		EnterpriseGradeEvaluationEntity egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluation(enterpriseId);
		if (egee != null && egee.getAuditState() == AuditStateEnum.UNAUDIT) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@Override
	public PageList<EnterpriseGradeEvaluationDetail> inquireEnterpriseGradeEvaluation(Long enterpriseId, String enterpriseName, Integer auditState, PageCriteria page) {
		PageList<EnterpriseGradeEvaluationEntity> pages = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationPageList(enterpriseId, enterpriseName, auditState, page);
		PageList<EnterpriseGradeEvaluationDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseGradeEvaluationEntity entity : pages) {
			results.add(EnterpriseCastor.toEnterpriseGradeEvaluationDetail(entity));
		}
		return results;
	}

	@Override
	@Transactional
	public void saveEnterpriseGradeAudit(Long gradeEvaluationId, Integer auditType, Boolean auditState, String audit, String approvalBooks) {
		EnterpriseGradeEvaluationEntity entity = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId);
		entity.setCallback(Boolean.FALSE);
		switch (auditType) {
		case 1:
			if (entity.getAuditSubmitState1() != null && entity.getAuditSubmitState1()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit1(audit);
			entity.setAuditState1(auditState);
			entity.setAuditDate1(DateUtil.now());
			entity.setAuditor1(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId1(FinanceSessionContext.getAccountId());
			break;
		case 2:
			if (entity.getAuditSubmitState2() != null && entity.getAuditSubmitState2()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit2(audit);
			entity.setAuditState2(auditState);
			entity.setAuditDate2(DateUtil.now());
			entity.setAuditor2(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId2(FinanceSessionContext.getAccountId());
			break;
		case 3:
			if (entity.getAuditSubmitState3() != null && entity.getAuditSubmitState3()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit3(audit);
			entity.setAuditState3(auditState);
			entity.setAuditDate3(DateUtil.now());
			entity.setAuditor3(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId3(FinanceSessionContext.getAccountId());
			break;
		case 4:
			if (entity.getAuditSubmitState4() != null && entity.getAuditSubmitState4()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit4(audit);
			entity.setAuditState4(auditState);
			entity.setAuditDate4(DateUtil.now());
			entity.setAuditor4(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId4(FinanceSessionContext.getAccountId());
			entity.setApprovalBooks(approvalBooks);
			break;
		case 5:
			if (entity.getAuditSubmitState5() != null && entity.getAuditSubmitState5()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit5(audit);
			entity.setAuditState5(auditState);
			entity.setAuditDate5(DateUtil.now());
			entity.setAuditor5(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId5(FinanceSessionContext.getAccountId());
			break;
		case 6:
			if (entity.getAuditSubmitState6() != null && entity.getAuditSubmitState6()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit6(audit);
			entity.setAuditState6(auditState);
			entity.setAuditDate6(DateUtil.now());
			entity.setAuditor6(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId6(FinanceSessionContext.getAccountId());
			break;
		case 7:	
			if (entity.getAuditSubmitState7() != null && entity.getAuditSubmitState7()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit7(audit);
			entity.setAuditState7(auditState);
			entity.setAuditDate7(DateUtil.now());
			entity.setAuditor7(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId7(FinanceSessionContext.getAccountId());
			break;
		case 8:	
			if (entity.getAuditSubmitState8() != null && entity.getAuditSubmitState8()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit8(audit);
			entity.setAuditState8(auditState);
			entity.setAuditDate8(DateUtil.now());
			entity.setAuditor8(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId8(FinanceSessionContext.getAccountId());
			break;
		case 9:	
			if (entity.getAuditSubmitState9() != null && entity.getAuditSubmitState9()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit9(audit);
			entity.setAuditState9(auditState);
			entity.setAuditDate9(DateUtil.now());
			entity.setAuditor9(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId9(FinanceSessionContext.getAccountId());
			break;
		case 10:	
			if (entity.getAuditSubmitState10() != null && entity.getAuditSubmitState10()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit10(audit);
			entity.setAuditState10(auditState);
			entity.setAuditDate10(DateUtil.now());
			entity.setAuditor10(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId10(FinanceSessionContext.getAccountId());
			break;
		case 11:	
			if (entity.getAuditSubmitState11() != null && entity.getAuditSubmitState11()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit11(audit);
			entity.setAuditState11(auditState);
			entity.setAuditDate11(DateUtil.now());
			entity.setAuditor11(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId11(FinanceSessionContext.getAccountId());
			break;
		case 12:	
			if (entity.getAuditSubmitState12() != null && entity.getAuditSubmitState12()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit12(audit);
			entity.setAuditState12(auditState);
			entity.setAuditDate12(DateUtil.now());
			entity.setAuditor12(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId12(FinanceSessionContext.getAccountId());
			break;
		default:
			break;
		}
		enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(entity);
	}

	@Override
	@Transactional
	public void submitEnterpriseGradeAudit(Long gradeEvaluationId, Integer auditType, Boolean auditState, String audit, String approvalBooks) {
		String tmp = "客户(%s)等级调整审批目前处于%s环节，请及时审批！";
		saveEnterpriseGradeAudit(gradeEvaluationId, auditType, auditState, audit, approvalBooks);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		FinanceAuditLogEntity fale = null;

		EnterpriseGradeEvaluationEntity entity = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId);
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(entity.getEnterpriseId());
		//1-业务经理 7-业务总监 8-业务副总  2-风控审核 9-风控领导 10-副总经理 3-总经理 4-风控批复 12-董事长 5-市场部确认 6-计财部确认 11-运营部确认 
		switch (auditType) {
		case 1:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "业务部:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState1()) {
				entity.setAuditSubmitState1(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.YWZJ.getCode());

				SendLetterMessage.sendLetterMessage("enterpriseManageAudit7_1", String.format(tmp, enterprise.getEnterpriseName(), "风控审核"));
			} else {
				initEnterpriseGradeEvaluation(entity);
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				opposeEnterpriseGradeEvaluation(entity.getGradeEvaluationId(), null);
			}
			break;
		case 2:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "风控部:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState2()) {
				entity.setAuditSubmitState2(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit9_1", String.format(tmp, enterprise.getEnterpriseName(), "风控领导"));
			} else {
				initEnterpriseGradeEvaluation(entity);
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit1_1", String.format(tmp, enterprise.getEnterpriseName(), "市场批复"));
			}
			break;
		case 3:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "总经理:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (Boolean.TRUE == entity.getAuditState3()) {
				entity.setAuditSubmitState3(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.RFK.getCode());
			
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit5_1", String.format(tmp, enterprise.getEnterpriseName(), "市场部确认"));
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit6_1", String.format(tmp, enterprise.getEnterpriseName(), "计财部确认"));
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit11_1", String.format(tmp, enterprise.getEnterpriseName(), "运营部确认"));

				EnterpriseGradeEvaluationEntity egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId);
				egee.setAuditDate(DateUtils.now());
				egee.setAuditor(FinanceSessionContext.getAccountFullName());
				egee.setAuditId(FinanceSessionContext.getAccountId());
				egee.setAuditState(AuditStateEnum.PASS);
				enterpriseGradeEvaluationService.auditEnterpriseGradeEvaluation(egee);

				FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId).getEnterpriseId(), "等级调整通过", "finance.enterprise.audit", "通过");

				EnterpriseSummaryTimeTask task = new EnterpriseSummaryTimeTask();
				task.countEnterpriseGradeEvaluation();
			} else {
				entity.setAudit3("");
				entity.setAuditDate3(null);
				entity.setAuditState3(Boolean.TRUE);
				entity.setAuditor3(null);
				entity.setAuditorId3(null);
				entity.setAuditSubmitState3(Boolean.FALSE);

				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 4:
			if (Boolean.TRUE == entity.getAuditState4()) {
				entity.setAuditSubmitState4(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.SCCWYY.getCode());
				fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "风控批复:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit5_1", String.format(tmp, enterprise.getEnterpriseName(), "市场部确认"));
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit6_1", String.format(tmp, enterprise.getEnterpriseName(), "计财部确认"));
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit11_1", String.format(tmp, enterprise.getEnterpriseName(), "运营部确认"));

				EnterpriseGradeEvaluationEntity egee = enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId);
				egee.setAuditDate(DateUtils.now());
				egee.setAuditor(FinanceSessionContext.getAccountFullName());
				egee.setAuditId(FinanceSessionContext.getAccountId());
				egee.setAuditState(AuditStateEnum.PASS);
				enterpriseGradeEvaluationService.auditEnterpriseGradeEvaluation(egee);

				FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId).getEnterpriseId(), "等级调整通过", "finance.enterprise.audit", "通过");

				EnterpriseSummaryTimeTask task = new EnterpriseSummaryTimeTask();
				task.countEnterpriseGradeEvaluation();
			} else {
				initEnterpriseGradeEvaluation(entity);
			}
			break;
		case 5:
			entity.setAuditSubmitState5(Boolean.TRUE);
			if (entity.getAuditSubmitState6() == Boolean.TRUE && entity.getAuditSubmitState11() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YY.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.CWYY.getCode());
			}

			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "市场部确认:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getGradeEvaluationId(), entity.getEnterpriseId(), ApiTypeEnum.YHDJ.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), enterprise.getEnterpriseName(), entity.getCreditLine());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 6:
			entity.setAuditSubmitState6(Boolean.TRUE);
			if (entity.getAuditSubmitState5() == Boolean.TRUE && entity.getAuditSubmitState11() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YY.getCode());
			} else if (entity.getAuditSubmitState5() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.RYW.getCode());
			} else if (entity.getAuditSubmitState5() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.SCYY.getCode());
			}


			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "计财部确认:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getGradeEvaluationId(), entity.getEnterpriseId(), ApiTypeEnum.YHDJ.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), enterprise.getEnterpriseName(), entity.getCreditLine());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 7:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "业务总监:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState7() == Boolean.TRUE) {
				entity.setAuditSubmitState7(Boolean.TRUE);
//				entity.setFinalState(ApiFinanceStateEnum.YWFZ.getCode());
//				SendLetterMessage.sendLetterMessage("enterpriseManageAudit8_1", String.format(tmp, enterprise.getEnterpriseName(), "业务副总"));
				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit2_1", String.format(tmp, enterprise.getEnterpriseName(), "业务副总"));
			} else {
				initEnterpriseGradeEvaluation(entity);
			}
			break;
		case 8:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState8() == Boolean.TRUE) {
				entity.setAuditSubmitState8(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit_2", String.format(tmp, enterprise.getEnterpriseName(), "风控审核"));
			} else {
				initEnterpriseGradeEvaluation(entity);
			}
			break;
		case 9:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "风控领导:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState9() == Boolean.TRUE) {
				entity.setAuditSubmitState9(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit10_1", String.format(tmp, enterprise.getEnterpriseName(), "副总经理"));
			} else {
				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit2("");
				entity.setAuditDate2(null);
				entity.setAuditState2(Boolean.TRUE);
				entity.setAuditor2(null);
				entity.setAuditorId2(null);
				entity.setAuditSubmitState2(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 10:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "副总经理:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState10() == Boolean.TRUE) {
				entity.setAuditSubmitState10(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.TMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit3_1", String.format(tmp, enterprise.getEnterpriseName(), "总经理"));
			} else {
				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 11:
			entity.setAuditSubmitState11(Boolean.TRUE);
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, "运营部确认:" + audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			//			entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			if (entity.getAuditSubmitState6() == Boolean.TRUE && entity.getAuditSubmitState5() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.RYW.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState5() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			} else if (entity.getAuditSubmitState6() == Boolean.FALSE && entity.getAuditSubmitState5() == Boolean.FALSE) {
				entity.setFinalState(ApiFinanceStateEnum.SCCW.getCode());
			}

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getGradeEvaluationId(), entity.getEnterpriseId(), ApiTypeEnum.YHDJ.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), enterprise.getEnterpriseName(), entity.getCreditLine());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 12:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getGradeEvaluationId(), Long.valueOf(ApiTypeEnum.YHDJ.getCode()), FinanceSessionContext.getAccountId());
			if (Boolean.TRUE == entity.getAuditState12()) {
				entity.setAuditSubmitState12(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.RFK.getCode());
				SendLetterMessage.sendLetterMessage("enterpriseManageAudit4_1", String.format(tmp, enterprise.getEnterpriseName(), "风控批复"));
			} else {
				entity.setAudit3("");
				entity.setAuditDate3(null);
				entity.setAuditState3(Boolean.TRUE);
				entity.setAuditor3(null);
				entity.setAuditorId3(null);
				entity.setAuditSubmitState3(Boolean.FALSE);

				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);
				
				entity.setAudit12("");
				entity.setAuditDate12(null);
				entity.setAuditState12(Boolean.TRUE);
				entity.setAuditor12(null);
				entity.setAuditorId12(null);
				entity.setAuditSubmitState12(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		default:
			break;
		}
		enterpriseGradeEvaluationService.updateEnterpriseGradeEvaluation(entity);
		financeAuditLogService.createFinanceAuditLogEntity(fale);
	}

	private void initEnterpriseGradeEvaluation(EnterpriseGradeEvaluationEntity entity) {
		entity.setAudit1("");
		entity.setAudit2("");
		entity.setAudit3("");
		entity.setAudit4("");
		entity.setAudit5("");
		entity.setAudit6("");
		entity.setAudit7("");
		entity.setAudit8("");
		entity.setAudit9("");
		entity.setAudit10("");
		entity.setAudit11("");
		entity.setAudit12("");
		entity.setAuditDate1(null);
		entity.setAuditDate2(null);
		entity.setAuditDate3(null);
		entity.setAuditDate4(null);
		entity.setAuditDate5(null);
		entity.setAuditDate6(null);
		entity.setAuditDate7(null);
		entity.setAuditDate8(null);
		entity.setAuditDate9(null);
		entity.setAuditDate10(null);
		entity.setAuditDate11(null);
		entity.setAuditDate12(null);
		entity.setAuditState1(Boolean.TRUE);
		entity.setAuditState2(Boolean.TRUE);
		entity.setAuditState3(Boolean.TRUE);
		entity.setAuditState4(Boolean.TRUE);
		entity.setAuditState5(Boolean.TRUE);
		entity.setAuditState6(Boolean.TRUE);
		entity.setAuditState7(Boolean.TRUE);
		entity.setAuditState8(Boolean.TRUE);
		entity.setAuditState9(Boolean.TRUE);
		entity.setAuditState10(Boolean.TRUE);
		entity.setAuditState11(Boolean.TRUE);
		entity.setAuditState12(Boolean.TRUE);
		entity.setAuditor1(null);
		entity.setAuditor2(null);
		entity.setAuditor3(null);
		entity.setAuditor4(null);
		entity.setAuditor5(null);
		entity.setAuditor6(null);
		entity.setAuditor7(null);
		entity.setAuditor8(null);
		entity.setAuditor9(null);
		entity.setAuditor10(null);
		entity.setAuditor11(null);
		entity.setAuditorId1(null);
		entity.setAuditorId2(null);
		entity.setAuditorId3(null);
		entity.setAuditorId4(null);
		entity.setAuditorId5(null);
		entity.setAuditorId6(null);
		entity.setAuditorId7(null);
		entity.setAuditorId8(null);
		entity.setAuditorId9(null);
		entity.setAuditorId10(null);
		entity.setAuditorId11(null);
		entity.setAuditorId12(null);
		entity.setAuditSubmitState1(Boolean.FALSE);
		entity.setAuditSubmitState2(Boolean.FALSE);
		entity.setAuditSubmitState3(Boolean.FALSE);
		entity.setAuditSubmitState4(Boolean.FALSE);
		entity.setAuditSubmitState5(Boolean.FALSE);
		entity.setAuditSubmitState6(Boolean.FALSE);
		entity.setAuditSubmitState7(Boolean.FALSE);
		entity.setAuditSubmitState8(Boolean.FALSE);
		entity.setAuditSubmitState9(Boolean.FALSE);
		entity.setAuditSubmitState10(Boolean.FALSE);
		entity.setAuditSubmitState11(Boolean.FALSE);
		entity.setAuditSubmitState12(Boolean.FALSE);
		entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
		entity.setCallback(Boolean.TRUE);
	}

	@Override
	public void consentEnterpriseGradeEvaluation(Long gradeEvaluationId, String auditRemark) {
		EnterpriseGradeEvaluationEntity e = new EnterpriseGradeEvaluationEntity();
		e.setGradeEvaluationId(gradeEvaluationId);
		e.setAuditDate(DateUtils.now());
		e.setAuditor(FinanceSessionContext.getAccountFullName());
		e.setAuditId(FinanceSessionContext.getAccountId());
		e.setAuditRemark(auditRemark);
		e.setAuditState(AuditStateEnum.PASS);
		enterpriseGradeEvaluationService.auditEnterpriseGradeEvaluation(e);

		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId).getEnterpriseId(), "等级调整通过", "finance.enterprise.audit", "通过");
	}

	@Override
	public void opposeEnterpriseGradeEvaluation(Long gradeEvaluationId, String auditRemark) {
		EnterpriseGradeEvaluationEntity e = new EnterpriseGradeEvaluationEntity();
		e.setGradeEvaluationId(gradeEvaluationId);
		e.setAuditDate(DateUtils.now());
		e.setAuditor(FinanceSessionContext.getAccountFullName());
		e.setAuditId(FinanceSessionContext.getAccountId());
		e.setAuditRemark(auditRemark);
		e.setAuditState(AuditStateEnum.REFUSE);
		enterpriseGradeEvaluationService.auditEnterpriseGradeEvaluation(e);

		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId).getEnterpriseId(), "等级调整通过", "finance.enterprise.audit", "拒绝");
	}
	//=======================================================================================================================================

	@Override
	public String adjustTemporaryCreditLine(TemporaryCreditlineEvaluation params) {
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		if (sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}

		if (StringUtils.isBlank(params.getEvaluationFileUuid())) {
			throw new BusinessException("评估表附件不允许为空");
		}
		TemporaryCreditlineEvaluationEntity entity = EnterpriseCastor.fromTemporaryCreditlineEvaluationDetail(params);
		entity.setAuditState(AuditStateEnum.UNAUDIT);
		entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
		entity.setAuditState1(Boolean.TRUE);
		entity.setAuditState2(Boolean.TRUE);
		entity.setAuditState3(Boolean.TRUE);
		entity.setAuditState4(Boolean.TRUE);
		entity.setAuditState5(Boolean.TRUE);
		entity.setAuditState6(Boolean.TRUE);
		entity.setAuditState7(Boolean.TRUE);
		entity.setAuditState8(Boolean.TRUE);
		entity.setAuditState9(Boolean.TRUE);
		entity.setAuditState10(Boolean.TRUE);
		entity.setAuditState11(Boolean.TRUE);
		entity.setAuditSubmitState1(Boolean.FALSE);
		entity.setAuditSubmitState2(Boolean.FALSE);
		entity.setAuditSubmitState3(Boolean.FALSE);
		entity.setAuditSubmitState4(Boolean.FALSE);
		entity.setAuditSubmitState5(Boolean.FALSE);
		entity.setAuditSubmitState6(Boolean.FALSE);
		entity.setAuditSubmitState7(Boolean.FALSE);
		entity.setAuditSubmitState8(Boolean.FALSE);
		entity.setAuditSubmitState9(Boolean.FALSE);
		entity.setAuditSubmitState10(Boolean.FALSE);
		entity.setAuditSubmitState11(Boolean.FALSE);
		entity.setCallback(Boolean.FALSE);
		entity.setAuditNumber(SettingConstants.PRE_AUDIT_NUMBER_ENTERPRISE + RandomUtil.generateTimeNumber());
		temporaryCreditlineEvaluationService.createTemporaryCreDitlineEvaluation(entity);

		FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), 1L, FinanceSessionContext.getAccountFullName() + "发起客户临时额度调整", entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(entity.getEnterpriseId());

		String tmp = "客户(%s)有新的临时额度，请及时审批！";
		SendLetterMessage.sendLetterMessage("temporaryAudit1_1", String.format(tmp, enterprise.getEnterpriseName(), "总经理"));

		return entity.toString();
	}

	@Override
	public TemporaryCreditlineEvaluationDetail inquireTemporaryCreditlineEvaluationDetail(
			Long temporaryCreditlineEvaluationId) {
		TemporaryCreditlineEvaluationEntity entity = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluation(temporaryCreditlineEvaluationId);
		return EnterpriseCastor.toTemporaryCreditlineEvaluationDetail(entity);
	}

	@Override
	public PageList<TemporaryCreditlineEvaluationDetail> inquireTemporaryCreditlineEvaluationPageList(String enterpriseName, Integer auditState, PageCriteria page) {
		PageList<TemporaryCreditlineEvaluationEntity> pages = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluationPageList(enterpriseName, auditState, page);
		PageList<TemporaryCreditlineEvaluationDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (TemporaryCreditlineEvaluationEntity temporaryCreditlineEvaluationEntity : pages) {
			TemporaryCreditlineEvaluationDetail detail = EnterpriseCastor.toTemporaryCreditlineEvaluationDetail(temporaryCreditlineEvaluationEntity);
			results.add(detail);
		}
		return results;
	}

	@Override
	public void consentTemporaryCreditlineEvaluation(Long temporaryCreditlineEvaluationId, String auditRemark) {
		TemporaryCreditlineEvaluationEntity e = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluation(temporaryCreditlineEvaluationId);
		e.setAuditDate(DateUtils.now());
		e.setAuditor(FinanceSessionContext.getAccountFullName());
		e.setAuditId(FinanceSessionContext.getAccountId());
		e.setAuditRemark(auditRemark);
		e.setAuditState(AuditStateEnum.PASS);
		temporaryCreditlineEvaluationService.updateTemporaryCreDitlineEvaluation(e);
		//		FinanceLetterBlockingQueue.putEnterpriseFinanceLetter(enterpriseGradeEvaluationService.inquireEnterpriseGradeEvaluationDetail(gradeEvaluationId).getEnterpriseId(), "等级调整通过", "finance.enterprise.audit", "通过");

	}

	@Override
	public void opposeTemporaryCreditlineEvaluation(Long temporaryCreditlineEvaluationId, String auditRemark) {
		TemporaryCreditlineEvaluationEntity e = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluation(temporaryCreditlineEvaluationId);
		e.setAuditDate(DateUtils.now());
		e.setAuditor(FinanceSessionContext.getAccountFullName());
		e.setAuditId(FinanceSessionContext.getAccountId());
		e.setAuditRemark(auditRemark);
		e.setAuditState(AuditStateEnum.REFUSE);
		temporaryCreditlineEvaluationService.updateTemporaryCreDitlineEvaluation(e);
	}

	@Override
	public void saveTemporaryCreditlineEvaluation(Long temporaryCreditlineEvaluationId, Integer auditType, Boolean auditState, String audit, String approvalBooks) {
		TemporaryCreditlineEvaluationEntity entity = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluation(temporaryCreditlineEvaluationId);
		entity.setCallback(Boolean.FALSE);
		switch (auditType) {
		case 1:
			if (entity.getAuditSubmitState1() != null && entity.getAuditSubmitState1()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit1(audit);
			entity.setAuditState1(auditState);
			entity.setAuditDate1(DateUtil.now());
			entity.setAuditor1(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId1(FinanceSessionContext.getAccountId());
			entity.setCallback(Boolean.FALSE);
			break;
		case 2:
			if (entity.getAuditSubmitState2() != null && entity.getAuditSubmitState2()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit2(audit);
			entity.setAuditState2(auditState);
			entity.setAuditDate2(DateUtil.now());
			entity.setAuditor2(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId2(FinanceSessionContext.getAccountId());
			break;
		case 3:
			if (entity.getAuditSubmitState3() != null && entity.getAuditSubmitState3()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit3(audit);
			entity.setAuditState3(auditState);
			entity.setAuditDate3(DateUtil.now());
			entity.setAuditor3(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId3(FinanceSessionContext.getAccountId());
			break;
		case 4:
			if (entity.getAuditSubmitState4() != null && entity.getAuditSubmitState4()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit4(audit);
			entity.setAuditState4(auditState);
			entity.setAuditDate4(DateUtil.now());
			entity.setAuditor4(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId4(FinanceSessionContext.getAccountId());
			entity.setApprovalBooks(approvalBooks);
			break;
		case 5:
			if (entity.getAuditSubmitState5() != null && entity.getAuditSubmitState5()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit5(audit);
			entity.setAuditState5(auditState);
			entity.setAuditDate5(DateUtil.now());
			entity.setAuditor5(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId5(FinanceSessionContext.getAccountId());
			break;
		case 6:
			if (entity.getAuditSubmitState6() != null && entity.getAuditSubmitState6()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit6(audit);
			entity.setAuditState6(auditState);
			entity.setAuditDate6(DateUtil.now());
			entity.setAuditor6(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId6(FinanceSessionContext.getAccountId());
			break;
		case 7:	
			if (entity.getAuditSubmitState7() != null && entity.getAuditSubmitState7()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit7(audit);
			entity.setAuditState7(auditState);
			entity.setAuditDate7(DateUtil.now());
			entity.setAuditor7(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId7(FinanceSessionContext.getAccountId());
			break;
		case 8:	
			if (entity.getAuditSubmitState8() != null && entity.getAuditSubmitState8()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit8(audit);
			entity.setAuditState8(auditState);
			entity.setAuditDate8(DateUtil.now());
			entity.setAuditor8(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId8(FinanceSessionContext.getAccountId());
			break;
		case 9:	
			if (entity.getAuditSubmitState9() != null && entity.getAuditSubmitState9()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit9(audit);
			entity.setAuditState9(auditState);
			entity.setAuditDate9(DateUtil.now());
			entity.setAuditor9(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId9(FinanceSessionContext.getAccountId());
			break;
		case 10:	
			if (entity.getAuditSubmitState10() != null && entity.getAuditSubmitState10()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit10(audit);
			entity.setAuditState10(auditState);
			entity.setAuditDate10(DateUtil.now());
			entity.setAuditor10(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId10(FinanceSessionContext.getAccountId());
			break;
		case 11:	
			if (entity.getAuditSubmitState11() != null && entity.getAuditSubmitState11()) {
				throw new BusinessException("该审核已提交，不能再次修改！");
			}
			entity.setAudit11(audit);
			entity.setAuditState11(auditState);
			entity.setAuditDate11(DateUtil.now());
			entity.setAuditor11(FinanceSessionContext.getAccountFullName());
			entity.setAuditorId11(FinanceSessionContext.getAccountId());
			break;
		default:
			break;
		}
		temporaryCreditlineEvaluationService.updateTemporaryCreDitlineEvaluation(entity);
	}

	@Override
	@Transactional
	public void submitTemporaryCreditlineEvaluation(Long temporaryCreditlineEvaluationId, Integer auditType, Boolean auditState, String audit, String approvalBooks) {
		String tmp = "客户(%s)临时额度调整审批目前处于%s环节，请及时审批！";
		saveTemporaryCreditlineEvaluation(temporaryCreditlineEvaluationId, auditType, auditState, audit, approvalBooks);
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		FinanceAuditLogEntity fale = null;
		TemporaryCreditlineEvaluationEntity entity = temporaryCreditlineEvaluationService.inquireTemporaryCreDitlineEvaluation(temporaryCreditlineEvaluationId);
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(entity.getEnterpriseId());
		//1-业务经理 7-业务总监 8-业务副总  2-风控审核 9-风控领导 10-副总经理 3-总经理 4-风控批复 12-董事长 5-市场部确认 6-计财部确认 11-运营部确认 
		switch (auditType) {
		case 1:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState1()) {
				entity.setAuditSubmitState1(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.YWZJ.getCode());

				SendLetterMessage.sendLetterMessage("temporaryAudit7_1", String.format(tmp, enterprise.getEnterpriseName(), "风控"));
			} else {
				opposeTemporaryCreditlineEvaluation(entity.getTemporaryCreditlineEvaluationId(), null);
				initTemporaryCreditlineEvaluation(entity);
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
			}
			break;
		case 2:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState2()) {
				entity.setAuditSubmitState2(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());

				SendLetterMessage.sendLetterMessage("temporaryAudit9_1", String.format(tmp, enterprise.getEnterpriseName(), "风控领导"));

			} else {
				initTemporaryCreditlineEvaluation(entity);
				SendLetterMessage.sendLetterMessage("temporaryAudit1_1", String.format(tmp, enterprise.getEnterpriseName(), "市场审核"));
			}
			break;
		case 3:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState3()) {
				entity.setAuditSubmitState3(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.RFK.getCode());

				SendLetterMessage.sendLetterMessage("temporaryAudit4_1", String.format(tmp, enterprise.getEnterpriseName(), "风控批复"));

			} else {
				entity.setAudit3("");
				entity.setAuditDate3(null);
				entity.setAuditState3(Boolean.TRUE);
				entity.setAuditor3(null);
				entity.setAuditorId3(null);
				entity.setAuditSubmitState3(Boolean.FALSE);

				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}  
			break;
		case 4:
			if (entity.getAuditState4() == Boolean.TRUE) {
				entity.setAuditSubmitState4(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.SCCWYY.getCode());
				SendLetterMessage.sendLetterMessage("temporaryAudit5_1", String.format(tmp, enterprise.getEnterpriseName(), "市场部确认"));
				SendLetterMessage.sendLetterMessage("temporaryAudit6_1", String.format(tmp, enterprise.getEnterpriseName(), "计财部确认"));
				SendLetterMessage.sendLetterMessage("temporaryAudit11_1", String.format(tmp, enterprise.getEnterpriseName(), "运营部确认"));

				entity.setAuditDate(DateUtils.now());
				entity.setAuditor(FinanceSessionContext.getAccountFullName());
				entity.setAuditId(FinanceSessionContext.getAccountId());
				entity.setAuditState(AuditStateEnum.PASS);
			} else {
				initTemporaryCreditlineEvaluation(entity);
				SendLetterMessage.sendLetterMessage("temporaryAudit1_1", String.format(tmp, enterprise.getEnterpriseName(), "市场审核"));
			}
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			break;
		case 5:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			entity.setAuditSubmitState5(Boolean.TRUE);
			//			entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			if (entity.getAuditSubmitState6() == Boolean.TRUE && entity.getAuditSubmitState11() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YY.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.CWYY.getCode());
			}

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getTemporaryCreditlineEvaluationId(), entity.getEnterpriseId(), ApiTypeEnum.LSED.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), enterprise.getEnterpriseName(), entity.getTemporaryCreditline());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 6:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			entity.setAuditSubmitState6(Boolean.TRUE);
			//			entity.setFinalState(ApiFinanceStateEnum.RYW.getCode());
			if (entity.getAuditSubmitState5() == Boolean.TRUE && entity.getAuditSubmitState11() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.YY.getCode());
			} else if (entity.getAuditSubmitState5() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.RYW.getCode());
			} else if (entity.getAuditSubmitState5() != Boolean.TRUE && entity.getAuditSubmitState11() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.SCYY.getCode());
			}

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getTemporaryCreditlineEvaluationId(), entity.getEnterpriseId(), ApiTypeEnum.LSED.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), enterprise.getEnterpriseName(), entity.getTemporaryCreditline());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		case 7:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState7() == Boolean.TRUE) {
				entity.setAuditSubmitState7(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.YWFZ.getCode());
				SendLetterMessage.sendLetterMessage("temporaryAudit8_1", String.format(tmp, enterprise.getEnterpriseName(), "业务副总"));
			} else {
				initTemporaryCreditlineEvaluation(entity);
			}
			break;
		case 8:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState8() == Boolean.TRUE) {
				entity.setAuditSubmitState8(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				SendLetterMessage.sendLetterMessage("temporaryAudit2_1", String.format(tmp, enterprise.getEnterpriseName(), "风控审核"));
			} else {
				initTemporaryCreditlineEvaluation(entity);
			}
			break;
		case 9:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState9() == Boolean.TRUE) {
				entity.setAuditSubmitState9(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.FMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("temporaryAudit10_1", String.format(tmp, enterprise.getEnterpriseName(), "副总经理"));
			} else {
				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit2("");
				entity.setAuditDate2(null);
				entity.setAuditState2(Boolean.TRUE);
				entity.setAuditor2(null);
				entity.setAuditorId2(null);
				entity.setAuditSubmitState2(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FK.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 10:
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			if (entity.getAuditState10() == Boolean.TRUE) {
				entity.setAuditSubmitState10(Boolean.TRUE);
				entity.setFinalState(ApiFinanceStateEnum.TMANAGE.getCode());
				SendLetterMessage.sendLetterMessage("temporaryAudit3_1", String.format(tmp, enterprise.getEnterpriseName(), "总经理"));
			} else {

				entity.setAudit9("");
				entity.setAuditDate9(null);
				entity.setAuditState9(Boolean.TRUE);
				entity.setAuditor9(null);
				entity.setAuditorId9(null);
				entity.setAuditSubmitState9(Boolean.FALSE);

				entity.setAudit10("");
				entity.setAuditDate10(null);
				entity.setAuditState10(Boolean.TRUE);
				entity.setAuditor10(null);
				entity.setAuditorId10(null);
				entity.setAuditSubmitState10(Boolean.FALSE);

				entity.setFinalState(ApiFinanceStateEnum.FKMANAGE.getCode());
				entity.setCallback(Boolean.TRUE);
			}
			break;
		case 11:
			entity.setAuditSubmitState11(Boolean.TRUE);
			fale = new FinanceAuditLogEntity(DateUtil.now(), sb.toString(), auditState?1L:0L, audit, entity.getTemporaryCreditlineEvaluationId(), Long.valueOf(ApiTypeEnum.LSED.getCode()), FinanceSessionContext.getAccountId());
			//			entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			if (entity.getAuditSubmitState6() == Boolean.TRUE && entity.getAuditSubmitState5() != Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.RYW.getCode());
			} else if (entity.getAuditSubmitState6() != Boolean.TRUE && entity.getAuditSubmitState5() == Boolean.TRUE) {
				entity.setFinalState(ApiFinanceStateEnum.ZJ.getCode());
			} else if (entity.getAuditSubmitState6() == Boolean.FALSE && entity.getAuditSubmitState5() == Boolean.FALSE) {
				entity.setFinalState(ApiFinanceStateEnum.SCCW.getCode());
			}

			if (entity.getAuditSubmitState5() && entity.getAuditSubmitState6() && entity.getAuditSubmitState11()) {
				entity.setFinalState(ApiFinanceStateEnum.FINISHED.getCode());
				entity.setAuditState(AuditStateEnum.FINISH);

				FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(entity.getTemporaryCreditlineEvaluationId(), entity.getEnterpriseId(), ApiTypeEnum.LSED.getCode(), entity.getAuditNumber(), Long.valueOf(FinanceAuditEnum.COMPLETED.ordinal()), DateUtil.now(), enterprise.getEnterpriseName(), entity.getTemporaryCreditline());
				financeAuditLogService.createFinanceCompleteResultEntity(fcre);
			}
			break;
		default:
			break;
		}
		financeAuditLogService.createFinanceAuditLogEntity(fale);
		temporaryCreditlineEvaluationService.updateTemporaryCreDitlineEvaluation(entity);
	}

	private void initTemporaryCreditlineEvaluation(TemporaryCreditlineEvaluationEntity entity) {
		entity.setAudit1("");
		entity.setAudit2("");
		entity.setAudit3("");
		entity.setAudit4("");
		entity.setAudit5("");
		entity.setAudit6("");
		entity.setAudit7("");
		entity.setAudit8("");
		entity.setAudit9("");
		entity.setAudit10("");
		entity.setAudit11("");
		entity.setAuditDate1(null);
		entity.setAuditDate2(null);
		entity.setAuditDate3(null);
		entity.setAuditDate4(null);
		entity.setAuditDate5(null);
		entity.setAuditDate6(null);
		entity.setAuditDate7(null);
		entity.setAuditDate8(null);
		entity.setAuditDate9(null);
		entity.setAuditDate10(null);
		entity.setAuditDate11(null);
		entity.setAuditState1(Boolean.TRUE);
		entity.setAuditState2(Boolean.TRUE);
		entity.setAuditState3(Boolean.TRUE);
		entity.setAuditState4(Boolean.TRUE);
		entity.setAuditState5(Boolean.TRUE);
		entity.setAuditState6(Boolean.TRUE);
		entity.setAuditState7(Boolean.TRUE);
		entity.setAuditState8(Boolean.TRUE);
		entity.setAuditState9(Boolean.TRUE);
		entity.setAuditState10(Boolean.TRUE);
		entity.setAuditState11(Boolean.TRUE);
		entity.setAuditor1(null);
		entity.setAuditor2(null);
		entity.setAuditor3(null);
		entity.setAuditor4(null);
		entity.setAuditor5(null);
		entity.setAuditor6(null);
		entity.setAuditor7(null);
		entity.setAuditor8(null);
		entity.setAuditor9(null);
		entity.setAuditor10(null);
		entity.setAuditor11(null);
		entity.setAuditorId1(null);
		entity.setAuditorId2(null);
		entity.setAuditorId3(null);
		entity.setAuditorId4(null);
		entity.setAuditorId5(null);
		entity.setAuditorId6(null);
		entity.setAuditorId7(null);
		entity.setAuditorId8(null);
		entity.setAuditorId9(null);
		entity.setAuditorId10(null);
		entity.setAuditorId11(null);
		entity.setAuditSubmitState1(Boolean.FALSE);
		entity.setAuditSubmitState2(Boolean.FALSE);
		entity.setAuditSubmitState3(Boolean.FALSE);
		entity.setAuditSubmitState4(Boolean.FALSE);
		entity.setAuditSubmitState5(Boolean.FALSE);
		entity.setAuditSubmitState6(Boolean.FALSE);
		entity.setAuditSubmitState7(Boolean.FALSE);
		entity.setAuditSubmitState8(Boolean.FALSE);
		entity.setAuditSubmitState9(Boolean.FALSE);
		entity.setAuditSubmitState10(Boolean.FALSE);
		entity.setAuditSubmitState11(Boolean.FALSE);
		entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
		entity.setCallback(Boolean.TRUE);
	}
	//=======================================================================================================================================
	@Override
	public String createFinanceFollowPerson(Long enterpriseId, Long employeeId, String clientNumber, Date dateStart,
			Date dateEnd) {
		FinanceEmployeeEntity ee = financeEmployeeService.inquireEmployee(employeeId);
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		FinanceFollowPersonEntity entity = new FinanceFollowPersonEntity();
		entity.setEnterpriseId(enterpriseId);
		entity.setClientName(enterprise.getEnterpriseName());
		entity.setClientNumber(clientNumber);
		entity.setDateEnd(dateEnd);
		entity.setDateStart(dateStart);
		entity.setFollowName(ee.getName());
		entity.setAccountId(ee.getAccountId());
		financeFollowPersonService.createFinanceFollowPerson(entity);
		return entity.getFollowId().toString();
	}

	@Override
	public void startAndStopFinanceFollowPerson(Long followId, String reason, String remark) {
		FinanceFollowPersonEntity entity = financeFollowPersonService.inquireFinanceFollowPerson(followId);
		entity.setReason(reason);
		entity.setRemark(remark);
		if (entity.getEnabled()) {
			entity.setEnabled(Boolean.FALSE);
		} else {
			entity.setEnabled(Boolean.TRUE);
		}
		financeFollowPersonService.updateFinanceFollowPerson(entity);
	}

	@Override
	public FinanceFollowPersonDetail inquireFinanceFollowPersonDetail(Long followId) {
		FinanceFollowPersonEntity entity = financeFollowPersonService.inquireFinanceFollowPerson(followId);
		return EnterpriseCastor.toFinanceFollowPersonDetail(entity);
	}

	@Override
	public List<FinanceFollowPersonDetail> inquireFinanceFollowPersonList(Long enterpriseId) {
		List<FinanceFollowPersonEntity> list = financeFollowPersonService.inquireFinanceFollowPersonList(enterpriseId);
		List<FinanceFollowPersonDetail> results = new ArrayList<>();
		for (FinanceFollowPersonEntity ffpe : list) {
			FinanceFollowPersonDetail detail = EnterpriseCastor.toFinanceFollowPersonDetail(ffpe);
			results.add(detail);
		}
		return results;
	}

	@Override
	public PageList<FinanceFollowPersonDetail> inquireFinanceFollowPersonPageList(String followName, String clientName,
			Date dateStart, Date dateEnd, PageCriteria page) {
		PageList<FinanceFollowPersonEntity> pages = financeFollowPersonService.inquireFinanceFollowPersonPageList(followName, clientName, dateStart, dateEnd, page);
		PageList<FinanceFollowPersonDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (FinanceFollowPersonEntity ffpe : pages) {
			FinanceFollowPersonDetail detail = EnterpriseCastor.toFinanceFollowPersonDetail(ffpe);
			results.add(detail);
		}
		return results;
	}

	@Override
	public String createFinanceFollowInfo(Long followId, String followType, Date date, String signLocation,
			String visitRemark, String visitFile, String visitImage, String visitAudio) {
		FinanceFollowInfoEntity entity = new FinanceFollowInfoEntity();
		entity.setFollowId(followId);
		entity.setFollowType(followType);
		entity.setDate(date);
		entity.setSignLocation(signLocation);
		entity.setVisitRemark(visitRemark);
		entity.setVisitAudio(visitAudio);
		entity.setVisitFile(visitFile);
		entity.setVisitImage(visitImage);
		financeFollowInfoService.createFinanceFollowInfo(entity);
		return entity.getFollowInfoId().toString();
	}

	@Override
	public void deleteFinanceFollowInfo(Long followInfoId) {
		FinanceFollowInfoEntity entity = financeFollowInfoService.inquireFinanceFollowInfo(followInfoId);
		if (entity.getSubmitState()) {
			throw new BusinessException("已提交的跟进信息不能删除！");
		}
		financeFollowInfoService.deleteFinanceFollowInfo(followInfoId);
	}

	@Override
	public void submitFinanceFollowInfo(Long followInfoId) {
		FinanceFollowInfoEntity entity = financeFollowInfoService.inquireFinanceFollowInfo(followInfoId);
		if (entity.getSubmitState()) {
			throw new BusinessException("已提交的跟进信息不能再次提交！");
		}
		entity.setSubmitState(Boolean.TRUE);
		financeFollowInfoService.updateFinanceFollowInfo(entity);
	}

	@Override
	public void deleteFinanceBulkstockPledgeRate(Long pledgeRateId) {
		financeBulkstockPledgeRateService.deleteFinanceBulkstockPledgeRate(pledgeRateId);
	}

	@Override
	public FinanceBulkstockPledgeRateDetail inquireFinanceBulkstockPledgeRate(Long enterpriseId, Long bulkstockInfoId,
			Integer productType) {
		EnterpriseGradeEntity ege = enterpriseGradeService.inquireEnterpriseGrade(enterpriseId);
		FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.inquireFinanceBulkstockPledgeRate(ege.getGradeEvaluationId(), bulkstockInfoId, ProductTypeEnum.valueOf(productType));
		if (fbpre == null) {
			throw new BusinessException("该企业尚不能做该货品融资！");
		}
		FinanceBulkstockPledgeRateDetail fbprd = new FinanceBulkstockPledgeRateDetail();
		BeanUtils.copyProperties(fbpre, fbprd);
		return fbprd;
	}

	@Override
	public Boolean existBulkstockPledgeRate(Long bulkstockInfoId, Integer productType, BigDecimal pledgeRate, BigDecimal loanRate, Long enterpriseId) {
		EnterpriseGradeEntity grade = null;
		//判断融资申请者
		if(null != enterpriseId) { //后台申请融资
			grade = enterpriseGradeService.inquireEnterpriseGrade(enterpriseId);
		}else { //客户融资申请
			grade = enterpriseGradeService.inquireEnterpriseGrade(FinanceSessionContext.getEnterpriseId());
		}
		 
		FinanceBulkstockPledgeRateEntity fbpre = financeBulkstockPledgeRateService.existBulkstockPledgeRate(bulkstockInfoId, grade.getGradeEvaluationId(), productType);
		if (pledgeRate != null) {
			if (fbpre.getPledgeRateCeiling().compareTo(pledgeRate) < 0) {
				throw new BusinessException("质押率大于所设定的上限");
			}
		}

		if (loanRate != null) {
			if (fbpre.getLoanRateCeiling().compareTo(loanRate) > 0) {
				throw new BusinessException("贷款率小于所设定的下限");
			}
		}

		if (fbpre == null) {
			return Boolean.FALSE;
		} else {
			return Boolean.TRUE;
		}
	}

	@Override
	public BusinessInfoDetailResult inquireEnterpriseBusinessInfoById(Long enterpriseId) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);

		String url = "http://api.qixin007.com/APITestService/v2/enterprise/getDetailById";
		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		params.put("id", "534472fd-7d53-4958-8132-d6a6242423d8");
		params.put("appkey", FinanceConstant.APP_KEY);
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		BusinessInfoDetailResult bean = JSON.toBean(responseText, BusinessInfoDetailResult.class);
		return bean;
	}

	@Override
	public EnterpriseLawsuitInfoDetailResult inquireEnterpriseLawsuitInfo(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/lawsuit/getLawsuitListById";
		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "534472fd-7d53-4958-8132-d6a6242423d8");
		params.put("appkey", "a0a01d53a236415699fb5f7f0788927f");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		EnterpriseLawsuitInfoDetailResult bean = JSON.toBean(responseText, EnterpriseLawsuitInfoDetailResult.class);
		return bean;
	}

	@Override
	public EnterpriseNoticeDetailResult inquireEnterpriseNotice(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/notice/getNoticeListById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "b5054e5b-8ce3-496b-a578-aaec562f65f5");
		params.put("appkey", "3a255067cbad41b685e985ece93d7965");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		EnterpriseNoticeDetailResult bean = JSON.toBean(responseText, EnterpriseNoticeDetailResult.class);
		return bean;
	}

	@Override
	public ExecutedPersonDetailResult inquireExecutedPerson(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/execution/getExecutedpersonListById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "94878eba-ddf0-41a9-9097-e6380badea8b");
		params.put("appkey", "1c71487e25eb4768bbe71d9833989e84");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		ExecutedPersonDetailResult bean = JSON.toBean(responseText, ExecutedPersonDetailResult.class);
		return bean;
	}

	@Override
	public ExecutionDetailResult inquireExecution(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/execution/getExecutionListById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "aa727091-edc5-4edc-b214-8119aa56b81f");
		params.put("appkey", "1c71487e25eb4768bbe71d9833989e84");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		ExecutionDetailResult bean = JSON.toBean(responseText, ExecutionDetailResult.class);
		return bean;
	}

	@Override
	public AuctionDetailResult inquireAuction(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/auction/getAuctionsListById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "32f4303b-afc7-4823-83ab-52e434d42a72");
		params.put("appkey", "16de47b84da345b98ec744d138b09f02");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		AuctionDetailResult bean = JSON.toBean(responseText, AuctionDetailResult.class);
		return bean;
	}

	@Override
	public AbnormalDetailResult inquireAbnormalList(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/abnormal/getAbnormalListById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "289f26e4-409c-4da9-962a-df2f66fe0dc1");
		params.put("appkey", "59297c9e0ade47f8b87915e3b0f4afaf");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		AbnormalDetailResult bean = JSON.toBean(responseText, AbnormalDetailResult.class);
		return bean;
	}

	@Override
	public OverDueTaxDetailResult inquireOverDueTax(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/overduetax/getOverDueTaxById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "fa9b370c-0106-48ec-96c5-b337e1cc11aa");
		params.put("appkey", "8aa2acad0dd949be85b295397d4ea759");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		OverDueTaxDetailResult bean = JSON.toBean(responseText, OverDueTaxDetailResult.class);
		return bean;
	}

	@Override
	public EquityQualitiesDetailResult inquireEquityQualities(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/equityPledge/getEquityQualitiesById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "74037a45-d954-4b96-9133-896ab5c00744");
		params.put("appkey", "08351BB4D71545AE8F1105374A2DF7B0");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		EquityQualitiesDetailResult bean = JSON.toBean(responseText, EquityQualitiesDetailResult.class);
		return bean;
	}

	@Override
	public MortgagesDetailResult inquireMortgages(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/mortgage/getMortgagesById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "74037a45-d954-4b96-9133-896ab5c00744");
		params.put("appkey", "9760b4bba8cc4cda8f5fc24e2b6db519");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		MortgagesDetailResult bean = JSON.toBean(responseText, MortgagesDetailResult.class);
		return bean;
	}

	@Override
	public CourtNoticeDetailResult inquireCourtNotice(Long enterpriseId, Integer skip) {
		//		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		String url = "http://api.qixin007.com/APITestService/courtnotice/getCourtNoticeById";

		Map<String, String> params = new HashMap<>();
		//		params.put("id", enterprise.getId());
		if (skip != null) {
			params.put("skip", skip.toString());
		}
		params.put("id", "534472fd-7d53-4958-8132-d6a6242423d8");
		params.put("appkey", "6e1e4ce5c2ba402ebcca8f4a75502ff6");
		String responseText = HttpClientHelper.post(url, params);
		System.out.println(responseText);
		CourtNoticeDetailResult bean = JSON.toBean(responseText, CourtNoticeDetailResult.class);
		return bean;
	}

	@Override
	public String createCommissionScaleTable(Long enterpriseId, String name, String personType, String fileUuids, BigDecimal rate, Integer type, Long accountId) {
		List<CommissionScaleTableEntity> list = commissionScaleTableService.inquireCommissionScaleTable(enterpriseId, accountId);
		if (list != null && list.size() > 0) {
			throw new BusinessException("不可重复添加");
		}
		CommissionScaleTableEntity entity = new CommissionScaleTableEntity();
		entity.setEnterpriseId(enterpriseId);
		entity.setName(name);
		entity.setRate(rate);
		entity.setType(type);
		entity.setAccountId(accountId);
		entity.setFileUuids(fileUuids);
		entity.setPersonType(personType);
		commissionScaleTableService.createCommissionScaleTable(entity);
		return entity.getScaleId().toString();
	}

	@Override
	public void updateCommissionScaleTable(Long scaleId, String name, String personType, String fileUuids, BigDecimal rate,
			Integer type, Long accountId) {
		CommissionScaleTableEntity entity = commissionScaleTableService.inquireCommissionScaleTableDetail(scaleId);
		if (Boolean.TRUE == entity.getEnable()) {
			throw new BusinessException("已启用的比例设定信息不能修改!");
		}
		entity.setName(name);
		entity.setRate(rate);
		entity.setAccountId(accountId);
		entity.setOperator(FinanceSessionContext.getAccountFullName());
		entity.setType(type);
		entity.setFileUuids(fileUuids);
		entity.setPersonType(personType);
		commissionScaleTableService.updateCommissionScaleTable(entity);
	}

	@Override
	public List<CommissionScaleTable> inquireCommissionScaleTableList(Long enterpriseId) {
		List<CommissionScaleTableEntity> list = commissionScaleTableService.inquireCommissionScaleTable(enterpriseId, null);
		List<CommissionScaleTable> result = new ArrayList<>();
		for (CommissionScaleTableEntity cste : list) {
			CommissionScaleTable detail = new CommissionScaleTable();
			BeanUtils.copyProperties(cste, detail);
			result.add(detail);
		}
		return result;
	}

	@Override
	public void enableCommissionScaleTable(Long scaleId) {
		CommissionScaleTableEntity entity = commissionScaleTableService.inquireCommissionScaleTableDetail(scaleId);
		if (Boolean.TRUE == entity.getEnable()) {
			entity.setEnable(Boolean.FALSE);
		} else {
			entity.setEnable(Boolean.TRUE);
		}
		commissionScaleTableService.updateCommissionScaleTable(entity);
	}

	@Override
	public void deleteCommissionScaleTable(Long scaleId) {
		CommissionScaleTableEntity entity = commissionScaleTableService.inquireCommissionScaleTableDetail(scaleId);
		if (Boolean.TRUE == entity.getEnable()) {
			throw new BusinessException("已启用的比例设定信息不能删除!");
		}
		commissionScaleTableService.deleteCommissionScaleTable(scaleId);
	}

	@Override
	public List<AssociatedPerson> inquireAssociatedPersonList(Long enterpriseId) {
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(enterpriseId);
		Map<String, String> params = new HashMap<>();
		params.put("customerName", enterprise.getEnterpriseName());

		List<AssociatedPerson> list = new ArrayList<>();
		String url = ConfigPropertites.getProperties("finance.getCustomerList.service");
		String responseText = HttpClientHelper.post(url, params);
		if (responseText != null) {
			CustomerListData results = JSON.toBean(responseText, CustomerListData.class);
			CustomerData result = results.getData();
			if (result != null) {
				if (result.getResponsible() != null) {
					AssociatedPerson ap = new AssociatedPerson();
					ap.setName(result.getResponsible().getResponsible_name());
					ap.setMobile(result.getResponsible().getResponsible_phone());
					ap.setPersonType("责任人");
					AccountNameEntity accountName = null;
					if (result.getResponsible().getIs_inside() == 0) {
						accountName = accountService.inquireAccountName(result.getResponsible().getResponsible_phone() + "@1");
					} else {
						accountName = accountService.inquireAccountName(result.getResponsible().getResponsible_phone());
					}
					if (accountName != null) {
						ap.setAccountId(accountName.getAccountId());
					}
					list.add(ap);
				}
				for (Sponsor s: result.getSponsor()) {
					AssociatedPerson ap = new AssociatedPerson();
					ap.setName(s.getSponsor_name());
					ap.setMobile(s.getSponsor_phone());
					ap.setPersonType("发起人");
					AccountNameEntity accountName = null;
					if (result.getResponsible().getIs_inside() == 0) {
						accountName = accountService.inquireAccountName(s.getSponsor_phone() + "@1");
					} else {
						accountName = accountService.inquireAccountName(s.getSponsor_phone());
					}
					if (accountName != null) {
						ap.setAccountId(accountName.getAccountId());
					}
					list.add(ap);
				}
				for (Campaigners c: result.getCampaigners()) {
					AssociatedPerson ap = new AssociatedPerson();
					ap.setName(c.getCampaigners_name());
					ap.setMobile(c.getCampaigners_phone());
					ap.setPersonType("参与人");
					AccountNameEntity accountName = null;
					if (result.getResponsible().getIs_inside() == 0) {
						accountName = accountService.inquireAccountName(c.getCampaigners_phone() + "@1");
					} else {
						accountName = accountService.inquireAccountName(c.getCampaigners_phone());
					}
					if (accountName != null) {
						ap.setAccountId(accountName.getAccountId());
					}
					list.add(ap);
				}
			}
		}
		return list;
	}

	@Override
	public String createSupplierInfo(SupplierInfo supplier) {
		SupplierEntity exist = supplierService.inquireSupplierDetail(supplier.getSupplierName());
		if (null != exist) {
			throw new BusinessException("该供应商已存在，不能重复添加！");
		}
		SupplierEntity entity = new SupplierEntity();
		BeanUtils.copyProperties(supplier, entity);
		if(FinanceSessionContext.isEnterprise()) {
			Long enterpriseId = FinanceSessionContext.getEnterpriseId();
			entity.setEnterpriseId(enterpriseId);
		}
		supplierService.createSupplier(entity);

		EnterpriseCastor.syncCustInfo(entity);

		return entity.getSupplierId().toString();
	}

	@Override
	public void updateSupplierInfo(SupplierInfo supplier) {
		SupplierEntity entity = new SupplierEntity();
		BeanUtils.copyProperties(supplier, entity);

		EnterpriseCastor.syncCustInfo(entity);

		supplierService.updateSupplier(entity);
	}

	@Override
	public void deleteSupplierInfo(Long supplierId) {
		supplierService.deleteSupplier(supplierId);
	}

	@Override
	public void disableSupplierInfo(Long supplierId) {
		SupplierEntity entity = supplierService.inquireSupplierDetail(supplierId);
		entity.setEnabled(Boolean.FALSE);
		supplierService.updateSupplier(entity);
	}

	@Override
	public void enableSupplierInfo(Long supplierId) {
		SupplierEntity entity = supplierService.inquireSupplierDetail(supplierId);
		entity.setEnabled(Boolean.TRUE);
		supplierService.updateSupplier(entity);
	}

	@Override
	public SupplierInfo inquireSupplierInfoDetail(Long supplierId) {
		SupplierEntity entity = supplierService.inquireSupplierDetail(supplierId);
		SupplierInfo detail = new SupplierInfo();
		BeanUtils.copyProperties(entity, detail);
		return detail;
	}

	@Override
	public List<SupplierInfo> inquireSupplierInfoList() {
		List<SupplierEntity> list = supplierService.inquireSupplierList();
		List<SupplierInfo> results = new ArrayList<>();
		for (SupplierEntity se : list) {
			SupplierInfo detail = new SupplierInfo();
			BeanUtils.copyProperties(se, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public PageList<SupplierInfo> inquireSupplierInfoPageList(PageCriteria page) {
		PageList<SupplierEntity> list = null;
		if (FinanceSessionContext.isEnterprise()) {
			list = supplierService.inquireSupplierPageList(FinanceSessionContext.getEnterpriseId(), page);
		} else {
			list = supplierService.inquireSupplierPageList(null, page);
		}
		PageList<SupplierInfo> results = new PageList<>(page, list.getTotalRecordCount());
		for (SupplierEntity se : list) {
			SupplierInfo detail = new SupplierInfo();
			BeanUtils.copyProperties(se, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public void syncSupplierInfo(Long supplierId) {
		SupplierEntity supplier = this.supplierService.inquireSupplierDetail(supplierId);
		EnterpriseCastor.syncCustInfo(supplier);
	}

	@Override
	public List<EnterpriseAddressInfo> inquireEnterpriseAddressList() {
		Long enterpriseID = FinanceSessionContext.getEnterpriseId();
		List<EnterpriseAddressEntity> list = enterpriseAddressService.inquireEnterpriseAddressList(enterpriseID);
		ArrayList<EnterpriseAddressInfo> results = new ArrayList<EnterpriseAddressInfo>();
		for (EnterpriseAddressEntity se : list) {
			EnterpriseAddressInfo detail = new EnterpriseAddressInfo();
			BeanUtils.copyProperties(se, detail);
			results.add(detail);
		}
		return results;
	}

	@Override
	public void createAddressInfo(EnterpriseAddressInfo enterpriseAddressInfo) {
		EnterpriseAddressEntity entity = new EnterpriseAddressEntity();
		BeanUtils.copyProperties(enterpriseAddressInfo, entity);
		if(FinanceSessionContext.isEnterprise()) {
			entity.setEnterpriseID(FinanceSessionContext.getEnterpriseId());
		}
		enterpriseAddressService.createAddressInfo(entity);
	}

	@Override
	public void updateAddressInfo(EnterpriseAddressInfo enterpriseAddressInfo) {
		EnterpriseAddressEntity entity = new EnterpriseAddressEntity();
		BeanUtils.copyProperties(enterpriseAddressInfo, entity);
		enterpriseAddressService.updateAddressInfo(entity);
	}

	@Override
	public EnterpriseAddressInfo inquireAddressInfoDetail(Long addressID) {
		EnterpriseAddressEntity entity = enterpriseAddressService.inquireAddressInfoDetail(addressID);
		EnterpriseAddressInfo enterpriseAddressInfo = new EnterpriseAddressInfo();
		BeanUtils.copyProperties(entity, enterpriseAddressInfo);
		return enterpriseAddressInfo;
	}

	@Override
	public void deleteAddressInfo(Long addressID) {
		enterpriseAddressService.deleteAddressInfo(addressID);
	}

	@Override
	public List<EnterpriseAddressInfo> inquireEnterpriseAddressPageList(
			PageCriteria page) {
		Long enterpriseId = null;
		if(FinanceSessionContext.isEnterprise()) {
			enterpriseId = FinanceSessionContext.getEnterpriseId();
		}
		PageList<EnterpriseAddressEntity> entity = enterpriseAddressService.inquireEnterpriseAddressPageList(enterpriseId,page);
		PageList<EnterpriseAddressInfo> results = new PageList<EnterpriseAddressInfo>(page, entity.getTotalRecordCount());
		for (EnterpriseAddressEntity addr : entity) {
			EnterpriseAddressInfo enterpriseAddressInfo = new EnterpriseAddressInfo();
			BeanUtils.copyProperties(addr, enterpriseAddressInfo);
			results.add(enterpriseAddressInfo);
		}
		return results;
	}
}
